Skip to content

Functions

Declaration

Functions are declared with the fn keyword. Parameters and return type are required.

fn add(a:i32, b:i32):i32 {
    return a + b
}

fn greet(name:string):void {
    console.log(name)
}

All parameter and return types follow the Type System rules, including i32, u8, number, string, bool, array, dict, and void.

Return Type

Functions that return a value use return:

fn multiply(a:number, b:number):number {
    return a * b
}

Functions that return nothing use :void:

fn print_header():void {
    console.log("===")
}

Return type mismatch produces a compile error:

fn double(x:number):string {
    return x * 2           # ERROR: expected string, got number
}

Argument Auto-Coercion

Number literals passed to integer parameters are auto-converted:

fn square(x:i32):i32 {
    return x * x
}

var result:i32 = square(5)   # 5 (number) auto-converted to i32

See Type System for full coercion rules.

Calling

Functions are called by name with parentheses:

var result:i32 = add(10, 32)
greet("stardyn")

Export

The export keyword makes a function visible to importers. Without export, functions are module-private.

package mylib

export fn add(a:i32, b:i32):i32 {
    return a + b
}

fn internal_helper():i32 {
    return 42
}

Only add is accessible via mylib.add(). internal_helper is not visible outside the module.

If no function in a module uses export, all functions are visible (backward compatible). Once any function is marked export, only exported functions are importable.

See Modules for details.

Native Function Stubs

In native modules, export fn without a body declares a function implemented in C:

package math

export fn sqrt(x: number): number
export fn pow(base: number, exp: number): number

The compiler emits OP_NATIVE_CALL for these — the VM dispatches directly to the registered C function.

Entry Point

fn main():void is required in package main files. The VM processes all top-level declarations first, then calls main().

package main

fn helper():i32 {
    return 42
}

fn main():void {
    var x:i32 = helper()
    console.log(x)
}