Array Functions

There are a few functions associated with the use of Arrays too. These are designed to give you flexibility in your code, and will permit you to create more functional and dynamic arrays when making your games.

Basic Array Functions

Advanced Array Functions

Extended Array Functions

Callback Method

A callback method is passed into an array function, such as array_foreach, along with an array.

GameMaker runs your callback method on each element of the given array. For each element in the array, it passes two arguments into your callback method:

In your callback method, you can use these arguments to calculate a return value, if the array function requires it (such as array_map).

Based on what your callback method returns for each element, either a result value or a modified copy of the array is returned. However if you're using one of the _ext functions, the original array is modified instead of being copied.

Predicate Method

When a callback method is required to only return true or false, it's called a predicate method. A predicate is used to tell whether an element in the array qualifies a condition.

Example: Predicate

Let's create a predicate method to check if an array contains the string "apple" inside it.

For this, we would use the array_any function:

var _array =
[
    "apple",
    "banana",
    "coconut",
    "dragonfruit"
]

var _contains_apple = array_any(_array, function(_val, _ind)
{
    return _val == "apple"
});

show_debug_message(_contains_apple); // prints 1 (true)

Our predicate method checks if _val == "apple" and returns the result. When this is true for any one of the array's elements, array_any returns true.

By default, a predicate method runs on all elements inside the array, however most advanced array functions also take two extra parameters: offset and length.

Offset And Length

The offset and length parameters let you decide which part of the array you want the function to look through, and which direction you want it to go (forwards or backwards).

If the function returns a modified version of the array, only the elements that were operated on will be returned, in the order they were operated in. For example, with an offset of 3 and length of 3, elements 3, 4, 5 will be operated on and returned as a new array, and the rest of the elements (e.g. 0, 1, 2, 6, 7, etc.) will be scrapped.