Skip to content

forEach

ffredyk edited this page Jul 23, 2026 · 1 revision

forEach

Category

Array

Arity

Binary<array> forEach { code }.

<array> forEach <code>

Description

Iterates over each element in the array, executing the given code block for each element. Inside the code block, magic variables provide access to the current element and index.

Magic Variables

Inside the forEach code block:

Variable Value
_x Current element
_forEachIndex Zero-based index
_this [element, index, array] (Arma SQF compat)

How It Works

The compiler inlines forEach into a loop over the array. For each iteration, it sets the magic variables and executes the code block. This is a compile-time construct — no runtime command lookup overhead.

Usage

Basic iteration

[1, 2, 3] forEach {
    systemChat f"Value: {_x}";
};

With index

_names = ["Alice", "Bob", "Charlie"];
_names forEach {
    systemChat f"{_forEachIndex}: {_x}";
};

Modifying elements (via index)

_arr = [1, 2, 3];
_arr forEach {
    _arr set [_forEachIndex, _x * 2];
};
// _arr is [2, 4, 6]

With _this (SQF compat)

_data forEach {
    _this params ["_element", "_index", "_array"];
    systemChat f"[{_index}] {_element}";
};

Filtering

_units = [unit1, unit2, unit3];
_alive = [];
_units forEach {
    if (_x get "alive") then { _alive pushBack _x };
};

Early exit

_arr forEach {
    if (_x == "target") exitWith {
        systemChat "Found!";
    };
};

Thread Safety

ReadOnly on the array (does not mutate). Code block may have side effects. Array must be accessible from current scheduler (frozen OK, mutable owned OK).

See Also

  • count — array length
  • select — element by index
  • pushBack — append during iteration
  • find — search for element

SQ# Wiki

Home

Engine Docs

Migration

Commands

Value Constructors

Arithmetic

Comparison

Logic

Array

String

Math

Random

Type & Introspection

HashMap

Code Execution

Concurrency

Scheduler

Thread Safety

Error

Output

Time

Multiplayer

Compiler

Clone this wiki locally