Skip to content
ffredyk edited this page Jul 23, 2026 · 1 revision

spawn

Category

Code Execution

Arity

Unary or Binary.

// Unary: no arguments
spawn { code }

// Binary: with arguments
<args> spawn { code }

Description

Executes a code block asynchronously in a new fiber on the current scheduler. Returns a ScriptHandle immediately — the code runs concurrently. The calling fiber continues without waiting.

Unlike call, spawn-executed code can suspendsleep and await work inside spawned code.

How It Works

This is a compiler-level construct. The compiler:

  1. Creates a new fiber on the current scheduler.
  2. Copies the arguments (if binary) into the fiber's context.
  3. Starts executing the code block.
  4. Returns a ScriptHandle to the caller.

The handle can be used to await completion, check status, or terminate the spawned code.

Usage

Unary spawn

_handle = spawn {
    sleep 5;
    systemChat "5 seconds passed";
};
// code continues immediately — does NOT wait for 5 seconds

Binary spawn (with args)

[100, "player"] spawn {
    params ["_hp", "_name"];
    sleep 2;
    systemChat f"{_name} has {_hp} HP";
};

Wait for completion

_handle = spawn { sleep 3; return "done"; };
_result = await _handle;       // waits for handle, returns "done"

Fire-and-forget

spawn { diag_log "background task"; };  // ignore handle

Multiple parallel tasks

_handles = [];
_handles pushBack (spawn { task1(); });
_handles pushBack (spawn { task2(); });
_handles pushBack (spawn { task3(); });

// Wait for all
{ await _x } forEach _handles;
systemChat "All tasks complete";

Return Values

The spawned code's return value is stored in the ScriptHandle. Retrieve with await:

_handle = spawn { sleep 1; return 42; };
_val = await _handle;          // 42

Thread Safety

Creates fiber on the current scheduler. The handle is owned by the spawning scheduler. Cross-scheduler spawn: use spawnOn.

See Also

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