Function values and arrow functions
Functions are values. Their type is written like a TypeScript function type.
type Op = (x: int) => int;
function triple(x: int): int { return x * 3; }
function apply(x: int, op: Op): int { return op(x); }
export function main(): void {
const inc: Op = (x) => x + 1; // parameter type from the context
const square = (x: int) => { return x * x; }; // the result type is inferred
print(apply(4, triple), apply(4, inc), square(5));
let maybe: Op | null = null;
print(maybe?.(2) ?? -1); // optional call
maybe = triple;
if (maybe != null) print(maybe(2));
}
12 5 25
-1
6
Rules
- Function types can appear anywhere a type can: parameters, results, locals, fields,
aliases, generic arguments. Parameter names don't matter for matching; parameter and
result types must match exactly (
cannot convert (arg1: int) => int to (arg1: float) => int). - Named functions (non-generic, module-level) can be used as values.
- An arrow can annotate its result type, as in
(x: int): int => x * 2. Without an annotation, the result comes from the context or is inferred from the body. - An arrow parameter needs a type annotation unless the context gives one
(
arrow parameter 'x' requires a type or a contextual function type). With a single untyped parameter the parentheses are optional:x => x + 1. - A nullable function is written
((x: int) => int) | null. Call it after narrowing, or withfn?.(x). Function values can only be compared withnull.
Captures are snapshots
An arrow captures the values of the variables it uses at the moment it is created. Later changes to those variables are not seen, and the arrow can't assign to them.
export function main(): void {
let offset = 2;
const add = (x: int) => x + offset;
offset = 100;
print(add(1)); // still 2 + 1
}
3
- Assigning to a captured variable is an error
(
cannot assign to captured variable 'count'), and so is capturing one that isn't assigned yet (captured variable 'value' is used before assignment). - Capturing a class reference or a collection copies the reference, so the arrow still sees and can change the object it points to.
- In a class method, an arrow captures
thisas a reference. In a struct method, it captures a copy ofthis. - A behavior's
objectsandobjcan't be captured; captureobj.handleinstead.
Lifetime
- A non-capturing arrow and a named function allocate nothing and can be stored anywhere except in components.
- A capturing arrow is allocated in the
framearena. Use it within the frame; storing it in longer-lived memory is rejected where the compiler can tell (frame allocation escapes into game storage). - Component fields can never hold function values, even
@transientones (component fields cannot store function values, including @transient fields). - Function values carry the gameplay module's generation. Calling one that was created by a previous version of the module (before a reload) stops the game with an error instead of jumping into unloaded code.