Molten

defer and calling C

defer

defer <statement>; runs the statement when the enclosing block exits, on every path out: falling off the end, return, break and continue. Several defers run in reverse order.

function work(): int {
    let result = 5;
    defer print("cleanup, result is", result);   // reads result at exit
    for (let i = 0; i < 3; i++) {
        defer print("end of pass", i);
        if (i == 1) break;
    }
    defer { result = 8; print("second defer"); }
    return result;                                // evaluated before the defers run
}

export function main(): void {
    print("returned", work());
}
end of pass 0
end of pass 1
second defer
cleanup, result is 8
returned 5
  • A defer is registered when execution reaches it. One that is never reached never runs.
  • It reads variables when it runs (at exit), not when it was registered.
  • A return expression is evaluated before the deferred statements run.
  • A deferred statement can't jump out of itself (control cannot leave a deferred statement): no return, break or continue inside it.
  • To defer inside an if or loop body, use a block: if (x) { defer f(); ... }.

Calling C functions

Gameplay modules can mix Cast with hand-written C in native/. Declare a C function or struct to use it from Cast:

declare function abs(value: int): int;
declare struct NativePoint { x: int; y: int; }

export function main(): void {
    const point = NativePoint(-7, 9);
    print(abs(point.x), point.y);
}
7 9
  • declare function uses the declared name as the C symbol and must have an explicit return type (this declaration requires a return type). The linker finds it in your native/ code or a linked library.
  • declare struct describes a C struct with a known layout: fields in order, explicit types, no defaults. It gets a positional constructor.

Calling Cast from C

castc writes game_generated.h with a C declaration for every exported function, struct and component. An exported Cast function select is called from C as cast_export_select(...). If your native/ code defines the module entry point (MOLTEN_MODULE), its on_load must call molten_cast_on_load(api) so the Cast components and behaviors are registered. samples/farmhouse/native/farmhouse.c shows a mixed game.

A game that has any .cast file compiles its whole gameplay module, including native/ C, with TinyCC in development. A game with only C uses MSVC (Windows) or gcc/clang (Linux). See castc output.

View this page's source on GitHub