Core Language

Semicolons are optional. GX accepts ; at the end of statements but does not require them.

Types

Scalars

i8, i16, i32, i64
u8, u16, u32, u64
f16, f32, f64
bool, str (fat string: {ptr, len}), char

char and bool are scalar values: characters compare with ==, !=, <, <=, >, >= (ch >= '0' && ch <= '9'), and booleans with == and !=.

A char and a one-byte integer (u8, i8, c_char, c_uchar) convert to each other without a cast. Indexing a str gives a byte (u8), so it goes straight into a char variable or a char parameter:

fn is_digit:bool(c: char) { return c >= '0' && c <= '9' }

var c: char = s[0]
if (is_digit(s[i])) { }
var b: u8 = 'A'             // 65

A wider integer needs the cast: (char)n.

Half precision (f16)

f16 is a 16-bit IEEE 754 floating-point type — the half of every shading language. It trades range and precision (~3 significant decimal digits) for 2-byte storage, which is what makes it the type you reach for when preparing data for the GPU: vertex attributes, weights, and large buffers where halving the element size halves bandwidth.

const HALF_PI:f16 = 3.140625      // nearest binary16 value to pi

struct Vertex {                   // 6 bytes — packs tight for a GPU buffer
    x: f16
    y: f16
    z: f16
}

Arithmetic on f16 promotes to f32 (the same rule C applies to _Float16), so intermediate results are computed at full single precision and only the stored value is narrowed back to half:

var a: f16 = 1.0
var b: f16 = 4.0
var mid: f16 = (a + b) * 0.5      // a+b is f32; the result narrows to f16

Backend representation. On the C backend f16 lowers to the C compiler’s native _Float16 when it is available (clang, gcc 12+) and to float otherwise (e.g. the bundled TCC — still correct, but 4-byte storage). On the LLVM backend it is always true half. See examples/54_f16.gx for a full walkthrough.

Vectors & Matrices

vec2, vec3, vec4
mat2, mat3, mat4

All are f32-based value types defined at the language level. See Vectors and Matrices below.

Pointers

var p:*i32;

fn log_text(text:const *char) { }   // `const *T` is a parameter type

Arrays

Fixed-size Arrays

var arr:i32[4] = {1, 2, 3, 4};

The size is a number, a top-level integer const, or a constant expression of those:

const GRID_W = 16
const GRID_H = 8

struct Row { tiles: i32[GRID_W] }

var cells:i32[GRID_W];
cells[GRID_W - 1] = 7;

var grid:i32[GRID_W * GRID_H];
var edges:f32[GRID_W + 1];

A size expression may use integer literals, top-level integer consts, the operators + - * / % << >>, unary minus and parentheses. It must come out positive. Anything else (a variable, a function call, a float) is a compile error: “Array size must be a compile-time integer constant”.

A const declared inside a function cannot be used as an array size.

Dynamic Arrays

Dynamic arrays (array<T>) auto-initialize on declaration — no .init() call needed:

var nums:array<i32>;
nums.push(10);
nums.push(20);
defer nums.free();

You can also initialize with values, just like fixed arrays:

var scores:array<i32> = {95, 82, 74, 88, 91};
var names:array<str> = {"Afan", "Sanela", "Ajdin"};

Indexing Dynamic Arrays

a[i] and a.at(i) are the same element access. Both work for reading and writing:

var nums:array<i32> = {5, 6, 7};
nums[1] = 60;             // write
nums[2] += 1;
var first = nums[0];      // read — same as nums.at(0)

var pts:array<Point>;
pts.push(Point{1.0, 2.0});
pts[0].x = 9.0;           // assign through an element
var p:*Point = &pts[0];   // valid until the next push

Both forms are bounds-checked. An index outside 0..len-1 stops the program:

panic: index 5 out of bounds (len 3)

The index expression is evaluated exactly once, so a[i++] advances i by one. The checks stay in at every -O level; pass --unchecked to remove them.

Iterating Arrays

Both fixed and dynamic arrays support for-each:

var data:i32[3] = {10, 20, 30};
for (var x in data) {
    print("{x}\n");
}

var items:array<str> = {"a", "b", "c"};
for (var item in items) {
    print("{item}\n");
}

Dynamic Array Methods

MethodDescription
.push(val)Append element
a[i] / .at(i)Bounds-checked element access, for reading and writing
.len()Current length
.cap()Current capacity
.sort()Sort (i32, u32, i64)
.clear()Remove all elements
.remove_swap(i)O(1) remove (swaps with last); no-op on an empty array
.remove_shift(i)O(n) remove (preserves order); no-op on an empty array
.free()Free backing memory

Collect Expressions

Build a dynamic array from a filtered loop:

var data:i32[6] = {5, 12, 3, 18, 7, 20};
var big = for (x in data) where (x >= 10) collect x;
// big is array<i32> containing {12, 18, 20}
big.free();

The source can be a fixed array, a slice or an array<T> (also as a struct field). The result is an array<T> of the source’s element type and must be freed.

Containers as Parameters

An array<T> or a map<K,V> can be a function parameter. Without out the function may read it; with out it works on the caller’s container, and the caller passes it with &, as for every out parameter.

fn total:i32(a: array<i32>) {             // read-only
    var t = 0
    for (i = 0:a.len() - 1) { t += a[i] }
    return t
}

fn squares(out a: array<i32>, n: i32) {   // writes to the caller's array
    a.clear()
    for (i = 1:n) { a.push(i * i) }
}

fn count:i32(m: map<str, i32>) { return m.len() }
fn put(out m: map<str, i32>, k: str, v: i32) { m.set(k, v) }

fn main() {
    var a: array<i32>
    squares(&a, 4)
    print("{total(a)}\n")                  // 30
    a.free()
}
  • A read-only container can be indexed, asked for len(), cap(), get() and has(), iterated, and passed on to another read-only parameter. Changing it is a compile error: push, set, clear, remove, sort and free, a write to an element (a[i] = v, a[i].x = v, a[i]++), and handing it or one of its elements to an out parameter.
  • Inside the function an out container is used like a local one (a.push(v), a[i] = v). To pass it on to another out parameter, write &a again.
  • A container field is passed the same way: total(mesh.ids), squares(&mesh.ids, 4).
  • Nothing is copied in either case: a read-only parameter shares the caller’s buffer, which is why it must not be changed or freed.
  • A channel is always out (out c: chan<T>, passed with &c): a channel is shared between its users, never copied.
  • A read-only container given to a slice parameter ([]T) is not checked: a slice’s elements are writable.
  • A function still cannot return a container; fill an out parameter.
  • A function-pointer type cannot name a container parameter yet (fn(array<i32>):i32).

The errors say what to write:

error: Argument 1: an 'out' parameter takes the address: pass it with '&'
error: Argument 1: this parameter is not 'out': pass the array<i32> itself, without '&'
error: Cannot call 'push' on a read-only parameter. Add 'out' to the parameter to allow modification.
error: Cannot write to read-only parameter 'a'. Add 'out' to the parameter to allow modification.
error: Argument 1: read-only parameter 'a' cannot be passed to an 'out' parameter. Add 'out' to it to allow modification.
error: A channel parameter must be 'out': a channel is shared, not copied. Write 'out c: chan<T>' and pass it with '&'.

Hash Maps

Hash maps (map<K,V>) provide key-value storage with O(1) average lookup. They auto-initialize on declaration — no .init() call needed:

var scores:map<str, i32>
scores.set("alice", 95)
scores.set("bob", 82)
defer scores.free()

print("alice: {scores.get("alice")}\n")   // 95
print("has bob: {scores.has("bob")}\n")   // true
print("len: {scores.len()}\n")            // 2

Key Types

Maps support two categories of keys:

  • String keys (str) — hashed by content using FNV-1a
  • Integer/enum keys (i32, u64, enum types, etc.) — hashed by raw bytes
// String-keyed
var names:map<str, i32>

// Integer-keyed
var lookup:map<i32, str>

A map<str, V> owns a copy of its keys. .set() copies the bytes of a new key into the map, so the key stays valid even when the string it was built from is gone. This matters for keys made by interpolation, which live in a temporary buffer:

var ids:map<str, i32>
defer ids.free()
for (i = 0:9) {
    ids.set("item{i}", i)         // the map keeps its own copy of "item0", "item1", ...
}
print("{ids.get("item7")}\n")     // 7

The copies are released by .remove(), .clear() and .free().

Hash Map Methods

MethodDescription
.set(k, v)Insert or update a key-value pair
.get(k)Get value by key (returns zero-value if missing)
.has(k)Check if key exists
.remove(k)Remove a key-value pair
.len()Number of entries
.clear()Remove all entries (keeps memory)
.free()Free backing memory

Iterating Maps

Destructured (two variables):

for (var name, score in scores) {
    print("{name}: {score}\n")
}

Entry-based (single variable with .key / .value):

for (var entry in scores) {
    print("{entry.key}: {entry.value}\n")
}

Both forms support where filtering:

for (var k, v in scores) where (v >= 80) {
    print("{k} passed with {v}\n")
}

for (var e in scores) where (e.value >= 80) {
    print("{e.key} passed with {e.value}\n")
}

Note: Iteration order is hash-order, not insertion-order.

Implementation

Under the hood, map<K,V> is an open-addressing hash table with linear probing:

  • 70% load factor — automatically grows and rehashes when exceeded
  • Power-of-2 capacity for fast modulo (h & (cap-1))
  • Tombstone-based deletion to preserve probe chains
// Grow/rehash is automatic
var m:map<i32, i32>
for (i = 0:99) {
    m.set(i, i * i)   // grows as needed
}
print("m[50] = {m.get(50)}\n")   // 2500
m.free()

Vectors

GX has built-in vector types for 2D, 3D, and 4D math — no imports needed:

TypeComponentsLayout
vec2x, y2 × f32
vec3x, y, z3 × f32
vec4x, y, z, w4 × f32

Construction

var a:vec2 = vec2{1.0, 2.0};
var b:vec3 = vec3{1.0, 2.0, 3.0};
var c:vec4 = vec4{1.0, 2.0, 3.0, 4.0};

Component Access

var v:vec3 = vec3{1.0, 2.0, 3.0};
var px:f32 = v.x;    // 1.0
var py:f32 = v.y;    // 2.0
v.z = 5.0;           // set z component

Arithmetic

Vector arithmetic uses standard runtime helpers:

var a:vec3 = vec3{1.0, 2.0, 3.0};
var b:vec3 = vec3{4.0, 5.0, 6.0};

var d:f32 = dot(a, b);        // dot product → f32
var c:vec3 = cross(a, b);     // cross product → vec3

String Conversion

Vectors support .str() and work in string interpolation:

var v:vec3 = vec3{1.0, 2.0, 3.0};
print("v = {v}\n");  // v = vec3(1, 2, 3)

Matrices

GX has built-in matrix types for 2D, 3D, and 4D transforms:

TypeLayoutColumn type
mat22 × 2vec2
mat33 × 3vec3
mat44 × 4vec4

All matrices are column-major (col[N] of vecN), matching OpenGL conventions.

Construction

var m:mat4 = identity_mat4();    // built-in identity constructor

Column Access

var m:mat4 = identity_mat4();
var first:vec4 = m.col[0];      // first column
var tx:f32 = m.col[3].x;        // translation X

Indexing returns the matching vector type: mat4.col[i] → vec4, mat3.col[i] → vec3, mat2.col[i] → vec2.

String Conversion

Matrices support .str() and string interpolation:

var m:mat2;
print("m = {m}\n");  // mat2([1,0], [0,1])

For transform helpers (perspective, look_at, rotation, etc.), see Math Module.

Operators

Arithmetic

+, -, *, /, %

Comparison

==, !=, <, <=, >, >=

Operands are numbers, enums, bool or char; strings compare with == / !=; pointers compare with each other and with null. Arithmetic or comparison on a whole struct or array is a compile error.

Logical

&&, ||, !

Bitwise

Bitwise operators work on integer types (i8–i64, u8–u64):

OperatorDescriptionExample
&Bitwise ANDflags & mask
|Bitwise ORflags | FLAG_READ
^Bitwise XORa ^ b
~Bitwise NOT~mask
<<Left shift1 << 4
>>Right shiftval >> 8
var flags:u32 = 0;
var FLAG_READ:u32 = 1 << 0;
var FLAG_WRITE:u32 = 1 << 1;
flags = flags | FLAG_READ;
if (flags & FLAG_READ) {
    print("readable\n");
}
var low_byte:i32 = 0xABCD & 0xFF;      // 205 (0xCD)
var high_byte:i32 = (0xABCD >> 8) & 0xFF;  // 171 (0xAB)

Hex literals are supported: 0xFF, 0xABCD.

Compound Assignment

+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

var x:i32 = 10;
x += 5;       // x = 15
x <<= 2;      // x = 60
x &= 0xFF;    // x = 60

Increment / Decrement

++ and -- work as both prefix and postfix operators:

var i:i32 = 0;
i++;           // postfix: evaluates to 0, then i = 1
++i;           // prefix: i = 2, evaluates to 2
i--;           // postfix: evaluates to 2, then i = 1

Ternary Operator

condition ? then_value : else_value

var x:i32 = 10;
var abs:i32 = x >= 0 ? x : -x;
var label:str = x > 5 ? "high" : "low";

Precedence (low to high)

  1. =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= (assignment, right-associative)
  2. ? : (ternary)
  3. ||
  4. &&
  5. |
  6. ^
  7. &
  8. ==, !=
  9. <, <=, >, >=
  10. <<, >>
  11. +, -
  12. *, /, %
  13. Unary: -, !, ~, & (address-of), * (deref), ++, --

Constants

Declare compile-time constants with const. The type can be inferred or explicitly annotated:

const PI = 3.14159265358979;
const TAU = PI * 2.0;
const SCREEN_WIDTH = 1920;
const MAX_ENTITIES:i32 = 1024;
const BUFFER_SIZE:i64 = MAX_ENTITIES * 64;

Constant Folding

The compiler evaluates constant expressions at compile time. Supported operations:

  • Arithmetic: +, -, *, /, %
  • Bitwise: &, |, ^, ~, <<, >>
  • Comparison: ==, !=, <, <=, >, >=
  • Logical: &&, ||, !
  • Unary: -, ~, !
  • References to other constants
  • Casts and ternary expressions
const FLAG_READ = 1;
const FLAG_WRITE = 2;
const FLAG_EXEC = 4;
const FLAG_ALL = FLAG_READ | FLAG_WRITE | FLAG_EXEC;  // folded to 7

const IS_WIDE = SCREEN_WIDTH > 1000;  // folded to true
const NEG_ONE = -1;
const NOT_FLAG = ~FLAG_READ;           // folded to -2

Scope

Constants work at both global and local scope:

const GLOBAL_MAX = 100;   // global

fn main() {
    const LOCAL_HALF = GLOBAL_MAX / 2;  // local
    print("{LOCAL_HALF}");
}

Assignment Protection

Assigning to a constant is a compile error:

const X = 10;
X = 20;  // ERROR: Cannot assign to constant

C Output

  • Global constants emit as static const type name = value;
  • Local constants emit as const type name = value;

The transpiler emits the folded literal value, not the original expression tree.

Const Arrays

Constants can hold fixed-size arrays of any type. The size may be given explicitly or inferred from the initializer with []:

const PRIMES:i32[5] = { 2, 3, 5, 7, 11 };
const COLORS:str[]  = { "red", "green", "blue" };  // size inferred to 3
const FIB:i64[]     = { 1, 1, 2, 3, 5, 8, 13, 21 };

Inference removes the need to keep the bracketed length in sync with the initializer — useful for word lists, lookup tables, and other long literals where a manual count would be error-prone.

C backend output: static const ec_str COLORS[3] = { ... }; (size baked in at compile time, no runtime overhead). JS backend output: const COLORS = ["red", "green", "blue"]; (length is intrinsic to the JS array).

Size inference currently applies to global-scope const arrays. Inside a function body, give the size explicitly: const X:i32[3] = { 1, 2, 3 };.

Defer

The defer statement schedules cleanup code to run when the enclosing block exits:

defer print("cleanup\n");
defer nums.free();
  • Multiple defers execute in LIFO (last-in, first-out) order; a function may have any number of them, in statement (defer f();) or block (defer { ... }) form
  • Defers run before return statements — return values are preserved
  • Block-scoped: defers in an if or for body run when that block ends

Allocators

GX provides three built-in allocator types for explicit memory management without new/delete:

Arena

A bump allocator — fast allocation, bulk-free only:

var arena:Arena;
arena.init(4096);
defer arena.destroy();

var p:*Point = arena.alloc(Point);
p.x = 3.14;

arena.mark();           // save position
var tmp = arena.alloc(Point);
arena.reset_to_mark();  // free everything since mark

arena.reset();          // free all allocations

Pool

Fixed-size slot allocator — O(1) alloc and free, ideal for uniform objects:

var pool:Pool;
pool.init(Point, 256);  // 256 slots of sizeof(Point)
defer pool.destroy();

var p:*Point = pool.alloc(Point);
pool.free(p);
pool.reset();  // free all slots

FreeList

Variable-size allocator with free-list coalescing:

var fl:FreeList;
fl.init(65536);
defer fl.destroy();

var p:*Point = fl.alloc(Point);
fl.free(p, Point);  // must specify type for size
fl.reset();
  • All allocators use defer allocator.destroy() for cleanup
  • alloc(T) returns *T — the type argument determines size and alignment
  • The memory returned by alloc(T) is zeroed, also after a reset() or a pool.free(), so every field starts at its zero value (and container fields start as valid empty containers)
  • No garbage collection — explicit free or bulk reset/destroy

Swizzle Operations

Reorder, duplicate, or extract components from vector types:

var v = vec3{1.0, 2.0, 3.0};
var a = v.xy;    // vec2(1, 2)
var b = v.zyx;   // vec3(3, 2, 1)
var c = v.xx;    // vec2(1, 1)
  • Valid components: x, y, z, w (must exist on the source type)
  • Length 1 → f32, length 2 → vec2, length 3 → vec3, length 4 → vec4
  • Components can repeat: v.xx, v.xxy

Implicit Widening

GX allows safe widening conversions automatically:

  • i8 → i16 → i32 → i64
  • u8 → u16 → u32 → u64
  • f16 → f32 → f64

Example:

var x:i32 = 100;
var y:i64 = x;   // OK

var f:f32 = 3.14;
var d:f64 = f;   // OK

Widening goes by size, so a same-size conversion (i32 → u32) is also implicit. Integer constants convert to any integer type their value fits:

var a:i8 = 100;      // OK — the constant fits
var b:u8 = 200;      // OK
var c:u8 = 300;      // ERROR — out of range

var big:i64 = 70000;
var d:u8 = big;      // ERROR — narrowing a variable needs a cast
var e:u8 = (u8)big;  // OK

Narrowing conversions require explicit casts — with one more exception: initializing a variable that is explicitly annotated f16 accepts a wider float literal directly, since the annotation already states the intent (the same way shading languages accept half h = 1.0;):

var h:f16 = 3.14159;   // OK — narrows into the annotated f16
var g:f32 = 3.14159265358979;   // ERROR — f64 literal, no f32 annotation rescue

Casting

var x:f32 = 3.14;
var i:i32 = (i32)x;

The target can be any scalar type, including the C types ((c_int)n, (c_size)len) and cstr ((cstr)byte_ptr, since v0.8.7). Pointer casts are written (*T)expr.

Sizeof

sizeof(T) returns the size in bytes of a type or expression as i64. Maps directly to C’s sizeof operator.

// Built-in types
var s1:i64 = sizeof(i32);     // 4
var s2:i64 = sizeof(f64);     // 8
var s3:i64 = sizeof(vec3);    // 12

// User-defined types (via expression)
var p:Point = Point{1.0, 2.0};
var s4:i64 = sizeof(p);       // 8 (two f32 fields)

// In expressions
var buf_size:i64 = 100 * sizeof(f32);

// Array types: the element count may be a constant expression
var s5:i64 = sizeof(f32[64]);      // 256
var s6:i64 = sizeof(Point[MAX + 1]);

Enums

enum Direction {
    North
    South
    East
    West
}
  • Stored as i32 internally
  • Members separated by newlines (commas optional)
  • Supports explicit values: North = 0

Explicit values follow C numbering: a member with = value gets that value, and a member without one is the previous member plus 1 (the first member defaults to 0).

enum Kind { KA  KB = 5  KC }                      // 0, 5, 6
enum Flag { FRead = 1  FWrite = 2  FExec = 4 }    // bit flags

var perms:i32 = (i32)FRead | (i32)FExec;          // 5

Struct Fields

A struct or union field can be any of the types below, not only scalars, pointers and other structs:

Field typeExample
Dynamic arrayverts: array<vec3>
Dynamic array of pointersparts: array<*Mesh>
Hash mapindex: map<str, i32>
Template instancebounds: Pair<f32>
Fixed array sized by a constweights: f32[MAX_WEIGHTS]
Sliceview: []i32
Function pointeron_change: fn(i32):i32
const MAX_WEIGHTS = 8

#type T
struct Pair { first: T  second: T }

struct Mesh {
    verts: array<vec3>
    index: map<str, i32>
    parts: array<*Mesh>
    bounds: Pair<f32>
    weights: f32[MAX_WEIGHTS]
    view: []i32
    on_change: fn(i32):i32
}

fn mesh_add(out m: *Mesh, name: str, v: vec3) {
    m.verts.push(v)                       // first push allocates
    m.index.set(name, m.verts.len() - 1)
}

fn main() {
    var m: Mesh                           // no allocation
    mesh_add(&m, "origin", vec3{0.0, 0.0, 0.0})
    mesh_add(&m, "tip", vec3{0.0, 1.0, 0.0})
    m.verts[1].y = 2.0
    print("{m.verts.len()} {m.index.get("tip")}\n")   // 2 1
    m.verts.free()
    m.index.free()
}

The zero value is a valid empty container. A zero-initialized struct, whether it is a local, a global, an element of a fixed array or memory from arena.alloc(T), holds empty arrays and maps. Nothing allocates until the first push or set, and there is no hidden constructor.

  • Copying a struct copies the container header and shares the buffer, the same as copying an array<T> variable
  • You still call .free() on each container yourself
  • Changing a container through a read-only pointer parameter is a compile error, both a modifying method (push, set, clear, remove, sort, free, …) and a write to an element (g.pts[i] = v); mark the parameter out (see Out Parameters)
  • A container field can be passed to a function on its own: see Containers as Parameters
  • A pointer to a container (*array<T>) is not supported as a field; store the container itself
  • Structs can be declared in any order: a struct may embed one that is declared later in the file

Unions

Unions allow multiple fields to share the same memory — only one field is valid at a time. They map directly to C union types.

union IntFloat {
    i: i32
    f: f32
}

Type Punning

Reinterpret raw bits between types:

var pun: IntFloat;
pun.i = 1065353216;     // IEEE 754 bits for 1.0
print("{pun.f}\n");     // 1.0

Tagged Union Pattern

Pair an enum tag with a union for safe variant storage:

enum ValueKind { IntVal FloatVal StrVal }

union ValueData {
    i: i32
    f: f32
    s: str
}

struct Value {
    kind: ValueKind
    data: ValueData
}

fn run() {
    var v: Value;
    v.kind = IntVal;
    v.data.i = 42;
}

Extern Unions

For C interop, declare external unions:

extern union my_c_union {
    value: i32
    bytes: u8[4]
}
  • Same field syntax as structs: name: Type
  • All fields overlap in memory (size = largest field)
  • Supports pointers, arrays, nested structs
  • Compiles to C union — zero overhead

Slices

A slice []T is a view into contiguous data — {ptr, len} — with no ownership and no copying:

var arr: i32[5] = {10, 20, 30, 40, 50};
var s: []i32 = arr;       // create slice from fixed array

s[0]                       // element access
s.len                      // 5 — O(1) length
s.ptr                      // typed pointer (*i32)
s[1:4]                     // subslice → {20, 30, 40, 50}, zero-copy
                            // inclusive on both ends: indices 1..4

Functions can take slices — fixed arrays and dynamic arrays implicitly convert:

fn sum:i32(data: []i32) {
    var total: i32 = 0;
    for (var x in data) { total += x; }
    return total;
}

var arr: i32[3] = {1, 2, 3};
sum(arr);                  // T[N] → []T implicit conversion

String Interpolation

Embed expressions directly in string literals with {expr}:

var name:str = "GX";
var val:i32 = 42;
print("Hello {name}, val={val}\n");
print("sum={10 + 20}\n");

Interpolated expressions are automatically wrapped in .str() calls and concatenated at compile time. This works with any type that supports .str().

The expression inside {} may contain string literals of its own, and a string can hold any number of interpolations:

print("alice: {scores.get("alice")}\n");
print("{a} + {b} + {c} = {a + b + c}, has bob: {scores.has("bob")}\n");

An interpolation must close on the line it starts on. A { that is not followed by the start of an expression (a letter, digit, _, (, -, ! or @) is plain text, so "{" + key + "}" stays three strings. For the same reason an interpolation cannot begin with a string literal; wrap it in parentheses instead: "{("a" + b)}".

Input

The input() built-in reads a line from stdin and returns it as str. An optional string argument is printed as a prompt before reading:

var name:str = input("What is your name? ");
print("Hello, {name}!\n");

var line:str = input();   // no prompt, just reads
  • Returns the line without the trailing newline
  • The prompt (if given) is flushed to stdout before blocking on stdin
  • Max line length: 1023 characters (uses the runtime temp buffer)

Control Flow

if (a > 5) { }
elif (a > 3) { }
else { }
while (a < 10) { }
for (i = 1:10) { }              // Inclusive range
for (var x in arr) { }          // For-each
for (var x in arr) where (x > 3) { }  // Filtered

Break and Continue

Use break to exit a loop early and continue to skip to the next iteration:

for (i = 0:100) {
    if (i > 10) { break; }
    if (i % 2 == 0) { continue; }
    print("{i}\n");
}

Match

The match statement provides clean multi-way branching — no fallthrough, no break needed:

var x:i32 = 2;
match (x) {
    1: print("one\n")
    2: print("two\n")
    3: print("three\n")
    default: print("other\n")
}

Comma-separated patterns match multiple values in one arm:

match (code) {
    1, 2, 3: print("low\n")
    4, 5, 6: print("mid\n")
    default: print("other\n")
}

Range patterns match a contiguous range of integers:

match (score) {
    0..59: print("F\n")
    60..69: print("D\n")
    70..79: print("C\n")
    80..89: print("B\n")
    90..100: print("A\n")
}

Match on enums for clean state/event dispatch:

enum State { Idle Running Stopped }

match (state) {
    Idle: start()
    Running: update()
    Stopped: cleanup()
}

Use braces for multi-statement arm bodies:

match (n) {
    1: {
        print("one ");
        print("(single)\n");
    }
    default: print("other\n")
}

Compiles to C switch/case with auto-break — zero overhead, jump-table eligible.

Collect Expressions

The collect keyword transforms a for-each loop into a value that produces a dynamic array:

var nums:i32[8] = {1, 2, 3, 4, 5, 6, 7, 8};

// Filter: keep only even numbers
var evens = for (n in nums) where (n % 2 == 0) collect n;

// Transform: double each element
var doubled = for (n in nums) collect n * 2;

// Filter + transform
var big = for (n in nums) where (n > 5) collect n * 10;

// Result is array<T> — use [i] / .at(i), .len(), .free()
print("count={evens.len()}\n");
evens.free();
doubled.free();
big.free();