The "foreach" Statement


foreach (DATA as "VALUE") call {


foreach (DATA as "KEY" of "VALUE") call {


Iterates through a given subject and returns the value of each item to a custom variable, which can be used to perform operations on each item in the subject.

Similar to a standard for loop, but with a more convenient syntax that shortcuts common loop operations. foreach supports iterating specific data types, including strings, arrays, all data structure types, and integers.

If it is necessary to know the current index of each iteration, a "key" custom variable can also be supplied before the custom value variable. The index will then be stored in the key for future reference.

Value and key variables must be input as strings, but will be referenced in custom code by their literal names instead.

Note that as, of, and call are special keywords for this function. Also note that the closing parenthesis comes before the call statement.

In the case of multidimensional arrays, only the dimension provided will be iterated. Any sub-dimensions will be returned in the custom value variable and can be handled in custom code.


Note that in some cases this function may not return the expected result due to the way GameMaker handles pointers. This means some types of data can share the same value, and whichever one happens to be first will take priority.


var my_array = ["a", "b", "c"];
var my_list = ds_list_create();
// Add each item in the example array to the example list
foreach (my_array as "letter" call) {
ds_list_add(my_list, letter);
// Add each item in the example list to the example array
foreach (my_list as "index" of "letter") call {
my_array[index] = letter;