Skip to content

Functions

ffredyk edited this page Jul 23, 2026 · 1 revision

Functions & Code

In SQ#, code blocks ({ ... }) are first-class values. They can be stored in variables, passed as arguments, returned from functions, and compiled at runtime.

Code Blocks as Values

// Store code in a variable
_double = { _this * 2 };
_result = 5 call _double;      // 10

// Pass code as argument
_processItems = {
    params ["_arr", "_fn"];
    _arr forEach { _x call _fn };
};
[[1, 2, 3], { print f"Got {_this}" }] call _processItems;

call — Synchronous Execution

Executes code immediately in the current fiber. Cannot suspend (sleep throws).

// Unary: no arguments
_result = call { 1 + 2; };     // 3

// Binary: _this = left operand
_result = [10, 20] call {
    params ["_a", "_b"];
    _a + _b                     // 30
};

// Call code variable
_triple = { _this * 3 };
_result = 7 call _triple;      // 21

spawn — Asynchronous Execution

Creates a new fiber on the current scheduler. Returns ScriptHandle. Can suspend.

// Unary spawn
_handle = spawn {
    sleep 2;
    print "Done after 2 seconds";
};

// Binary spawn (with args)
[100, "player"] spawn {
    params ["_hp", "_name"];
    sleep 1;
    print f"{_name} HP: {_hp}";
};

// Wait for result
_handle = spawn { sleep 1; return 42; };
_result = await _handle;       // 42

execVM — Load & Spawn File

Reads an .sqf file from disk, compiles it, and spawns:

_handle = execVM "scripts\init.sqf";
await _handle;
print "Init complete";

compile — Runtime Compilation

Compiles a source string into a Code value:

_code = compile "(_this select 0) * 2";
_result = 5 call _code;        // 10

// Dynamic code from user input
_expr = compile _userFormula;
_result = call _expr;

// Store and reuse
_add = compile "(_this select 0) + (_this select 1)";
[3, 4] call _add;              // 7

Warning: compile on untrusted input is a security risk. Validate carefully.

params — Argument Destructuring

Destructures an array into named local variables:

_arr = [42, "hello", true];
_arr params ["_num", "_str", "_flag"];

// With defaults
_arr params ["_num", ["_opt", 99]];  // _opt = 99 if missing

// With type checks
_arr params [["_num", "number"], ["_name", "string"]];

params is a compiler-level construct — inlined at compile time, no runtime overhead.

Function Patterns

Function Factories (Closures)

_makeMultiplier = {
    params ["_factor"];
    compile f"(_this * {_factor})"
};

_double = [2] call _makeMultiplier;
_triple = [3] call _makeMultiplier;
5 call _double;                // 10
5 call _triple;                // 15

Higher-Order Functions

_map = {
    params ["_arr", "_fn"];
    _result = [];
    { _result pushBack (_x call _fn) } forEach _arr;
    _result
};

_doubled = [[1, 2, 3], { _this * 2 }] call _map;  // [2, 4, 6]

Recursion

_factorial = {
    params ["_n"];
    if (_n <= 1) exitWith { 1 };
    _n * ([_n - 1] call _factorial)
};

[5] call _factorial;           // 120

Compose

_compose = {
    params ["_f", "_g"];
    compile f"((_this call {str _g}) call {str _f})"
};

_double = { _this * 2 };
_addOne = { _this + 1 };
_doubleAfterAdd = [_double, _addOne] call _compose;
5 call _doubleAfterAdd;        // 12 ((5+1)*2)

Global Functions

// Define global function
global fn_healthCheck = {
    params ["_unit", "_threshold"];
    (_unit get "hp") < _threshold
};

// Call from anywhere
_result = [player, 25] call fn_healthCheck;

Execution Context Comparison

call spawn execVM callUnscheduled
Returns Last expression ScriptHandle ScriptHandle Last expression
New fiber? No Yes Yes No
Can suspend? Inherits caller ✅ Yes ✅ Yes ❌ No
Use case Sync computation Async work Load file Performance-critical
_this Left operand Left operand
Scheduler Caller's Current Current None

See Also

  • Control Flow — if/while/for/switch
  • Concurrency — spawn/await/sleep/timeout
  • call — call command reference
  • spawn — spawn command reference
  • execVM — execVM command reference
  • compile — compile command reference
  • params — params destructuring reference

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