Game Maker Games, Articles, Tutorials & More

Game Maker Network


Howdy, Guest! Please sign in or register an account.

Print

string_generate

By Daniel · January 11, 2009

Generate a string based on the given format, mimicking the behavior of printf in other languages. This is a simplified version of the routine, so it only supports the following specifiers (and no parameters):

%d or %i: integer
%x: hexadecimal
%f: floating point
%s: string

For example, string_generate("... %d, %f, %s ...", pi, pi, "hello") yields "... 3, 3.14, hello ..."

/* string_generate(format, datum1, datum2, ...)
 *
 * Generate a string based on the given format, mimicing the behavior of
 * printf in other languages. This is a simplified version of the routine,
 * so it only supports the following specifiers (and no parameters):
 *
 * %d or %i: integer
 * %x: hexadecimal
 * %f: floating point
 * %s: string
 *
 * For example, string_generate("... %d, %f, %s ...", pi, pi, "hello")
 * yields "... 3, 3.14, hello ..."
 */

var a, p, t;

for (a = 1; true; a += 1) {
  p = string_pos('%', argument0);
  if (p < 1) break;
  t = string_char_at(argument0, p + 1);
  
  switch (t) {
    // Integer
    case 'd':
    case 'i':
      argument0 = string_replace(argument0, '%d', string(floor(argument[a])));
      break;
    
    // Hex
    case 'x':
      var lang, hex, neg;
      lang = '0123456789ABCDEF';
      hex = '';
      neg = (sign(argument[a]) == -1);
      if (neg) argument[a] *= -1;
      
      while (argument[a]) {
        hex = string_char_at(lang, (argument[a] & 15) + 1) + hex;
        argument[a] = argument[a] >> 4;
      }
      if (neg) hex = '-' + hex;
      argument0 = string_replace(argument0, '%x', hex);
      break;
    
    // Float
    case 'f':
      argument0 = string_replace(argument0, '%f', string(argument[a]));
      break;
    
    // String
    case 's':
      argument0 = string_replace(argument0, '%s', argument[a]);
      break;
    
    default:
      return 'error';
  }
}

return argument0;

Categories: String handling

Comments

There are no comments to display.

Post a Comment

You must be signed in to post comments.

Advertisement