The "foreach" Statement
#
Syntax#
Or#
DescriptionIterates 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 arrays, data structures, integers, objects, and strings.
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.
In the case of objects, iteration will be performed through all active instances of an object in the current room.
caution
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.