string_foreach

This function executes a callback function on all characters of the given string.

The function optionally takes in a starting position and a length that define the range of characters over which to iterate, and the direction of iteration (left-to-right or right-to-left).

The callback function will receive two arguments for each character in the string: the character itself, and its position in the string.

IMPORTANT In GameMaker, string positions start at 1 (meaning they are one-based), compared to other data types in GameMaker, which are all zero-based (starting at 0). So the first character in a string has a position of 1, the second character a position of 2, and so on. The last character is string_length(string).

 

Syntax:

string_foreach(string, function, [pos], [length]);

ArgumentTypeDescription
stringStringThe string to iterate over
functionFunctionThe function to execute for each of the characters in the range, with arguments character and position
posRealOPTIONAL The starting position (default is 1 for strings). Negative values count from the end of the string (e.g. -1 is the position of the last character, -2 is the position of the one before last character, etc.). 0 is treated the same as 1.
lengthRealOPTIONAL The number of characters to iterate over and the direction in which to iterate (left-to-right (positive value) or right-to-left (negative value)).

 

Returns:

N/A

 

Example 1:

function debug_character(character, position)
{
    show_debug_message(character);
}

string_foreach("test", debug_character);

The above code first defines a function debug_character that prints the character to the log using show_debug_message. It then calls the function string_foreach on a string "test" to execute the debug_character function on all its characters.

 

Example 2:

function debug_extended(character, position)
{
    show_debug_message("{0}: {1}", position, character);
}

string_foreach("1234567890", debug_extended, -1, -infinity);

The above code first defines a function debug_extended that shows a debug message with both the position and the character in it. Then, string_foreach is called with the debug_extended function on the string "1234567890". Because the offset is -1, the first character on which the function will execute is the last one ("0"). The characters are traversed in a descending order because of the negative length ("0", "9", "8", "7", "6", ..., "1").