array_foreach

This function loops through an array (or a range of it) and executes the Callback Method for each element.

IMPORTANT You cannot use this function to change array elements directly, i.e. by writing  element = value;  in the function. You can make changes if the array element references something else (e.g. when the array element itself is an array or struct).

Callback FunctionCallback Function

The callback function you pass into this function should take the following arguments:

Syntax:

function(element, index);

ArgumentTypeDescription
elementAnyThe current array element
indexRealThe current array index

This callback function should not return a value. It simply executes the function on all elements in the given range.

 

Syntax:

array_foreach(array, function, [offset], [length]);

ArgumentTypeDescription
arrayArrayThe array to use
functionFunctionThe callback function to run on each element
offsetRealOPTIONAL The offset, or starting index, in the array. Setting a negative value will count from the end of the array. The starting index will then be array_length(array) + offset. See: Offset And Length
lengthRealOPTIONAL The number of elements to traverse. A negative value will traverse the array backwards (i.e. in descending order of indices, e.g. 2, 1, 0 instead of 2, 3, 4). See: Offset And Length

Returns:

N/A

 

Example:

var _array =
[
    { x: 4,  y: 5  },
    { x: 12, y: 8  },
    { x: 75, y: 23 }
];

var _set_x_to_index = function(_element, _index)
{
    _element.x = _index;
}

array_foreach(_array, _set_x_to_index);

The above code first creates a temporary array of structs array where each struct stores and x and y value.

It then defines a temporary function x_to_index that takes in an element and an index, and sets the element's x to that index.

It expects the element parameter to be a struct. Finally array_foreach is called with the array and the function as the arguments. After the code has executed all structs will have their x value set to their array index.