Scripting
Balaur Script: typed .bs files compiled to WebAssembly, with lifecycle hooks, exported properties, await, hot reload that keeps state, and a debugger.
On this page
Scripts are Balaur Script: .bs files attached to nodes in a scene. The
language is statically typed, reads like Rust, and compiles to WebAssembly.
The model
// scripts/spinner.bs
pub class Spinner {
pub speed: float = 2.0,
node: Node,
angle: float,
}
impl Spinner {
fn init() {
self.angle = 0.0;
}
fn update(dt: float) {
self.angle += dt * self.speed;
self.node.transform.rotation_euler = vec3(0.0, self.angle, 0.0);
}
fn fixed_update(dt: float) {} // the fixed 60 Hz step, before physics
}
| Hook | When |
|---|---|
init |
once, after the properties are written |
update(dt) |
once a frame, with the measured frame time |
fixed_update(dt) |
on the fixed 60 Hz step, before physics. Simulation belongs here |
on_free |
before the node or the script goes |
- The file's
pub classis the script, named after the file:door_bell.bsholdsDoorBell. Each node it is attached to holds one instance of it. - A field named
nodeof typeNodeis set to the node the instance sits on. - Inside
impl,selfis the instance:self.angle,self.node. - See Determinism for what belongs in which hook.

The language
| Has | Example |
|---|---|
int (64-bit), float (64-bit), bool, str |
let n = 3; let x: float = 0.5; |
Vec2, Vec3, Color |
vec3(0.0, 1.0, 0.0), p.x |
| Lists | [1, 2, 3], [0.0; 16], xs.push(4), xs.len() |
| Optional values | let hit: Node? = nil; hit != nil, hit.unwrap() |
| Structs, copied as values | struct Wave { hp: int, name: str } |
| Classes, one object every holder shares | class Board { cells: [int] } |
| Free-form data | any: an HTTP reply, a save, a map written { "k": v } |
| Enums | enum Shape { Circle(float), Empty }, match s { Shape::Circle(r) => r, Shape::Empty => 0.0 } |
| Function values | let f: fn(int) -> int = double; |
| A caller's value, written back | fn grow(w: &mut Wave) { w.hp += 1; } |
if as a value |
let sign = if self.clockwise { 1.0 } else { -1.0 }; |
| Loops | while, loop, for i in 0..n, for x in xs |
| Interpolation | "hp {self.hp} of {MAX}" |
| Async | async fn, await task::seconds(0.5); |
- An integer meets a float as a float:
1 + 0.5is1.5.asconverts the rest. - Enums with
match. No generics, traits or closures: a function value names a function. Balaur Script teaches the language, one concept a page. - Strings and lists are reference counted. Nothing is collected in the background, so nothing a game sees depends on when a collector runs.
- A cycle of classes leaks.
Properties
Every pub field is a property the inspector shows and a scene sets,
whatever its type. An internal or unmarked field stays the script's own.
pub class Spinner {
/// Turns a second.
pub speed: float = 2.0,
pub clockwise: bool = true,
pub target: Node,
pub stops: [float],
node: Node,
}
[nodes.script]
source = "scripts/spinner.bs"
[nodes.script.props]
speed = 3.5
target = "../Wheel"
stops = [0.25, 0.75]
- The type picks the inspector's row: a number, a toggle, text, a node
picker, a list, a
{str: V}table, a struct's fields or an enum's variants. A transform is its axes and its origin. - A scene cannot write an
anyor afn, so apubfield holding one does not compile: mark itinternal. - A default may be an
int, afloat, aboolor astrliteral. A field without one starts empty. - The
///lines above a field are what the inspector says of it. - The defaults are written onto the instance, the node's
propsover them, theninitruns. - The inspector writes an override only where the value differs from the default.
node.attach_script(path, props)does the same at run time.
Modules
Engine modules are reached with ::. Every call is typed against the engine
the script compiles for.
let t = engine::time();
let ball = scene::root().get_node("World/Ball");
self.node.set_component("body3d", { "kind": physics3d::BODY_DYNAMIC });
engine, scene, log, input, random, math, physics, physics2d,
physics3d, render, audio, ui, animation, skeleton, assets,
http, websocket, events, task, fs, toml, json, and more. Every
function and constant is in the
script modules reference, generated from a booted
engine.
| Shape | Example |
|---|---|
| Named values, never spelled | input::KEY_SPACE, physics3d::BODY_DYNAMIC, ui::ANCHOR_TOP_LEFT |
| Node operations are methods | self.node.get_node("../Target"), node.queue_free() |
| Two or three numbers are a vector | input::mouse_position().x |
| A record is a struct | log::since(cursor).entries, ui::widget_rect(n).unwrap().width |
Free-form data is an any |
r["status"], r["body"], { "kind": "sphere" } |
| Trailing optional arguments may be left out | log::since() |
A component's operations are methods on its field of the node:
self.node.body2d.apply_impulse(x, y). A module keeps what belongs to no
node, such as physics2d::raycast. The
component reference lists the operations per
component.
self.node.body2d.apply_impulse(0.0, 12.0);
if self.node.body2d.linear_velocity().x > 5.0 {
self.node.body2d.set_linear_velocity(5.0, 0.0);
}
A component's properties are fields. A script moves a node by writing its
transform:
let p = self.node.transform.position;
self.node.transform.position = vec3(p.x, p.y + 1.0, p.z);
self.node.transform.rotation_euler = vec3(0.0, math::to_radians(90.0), 0.0);
- Rotations are euler radians, x then y then z.
math::to_degreesandmath::to_radiansconvert; the inspector shows degrees. - A node without a
transformreads its schema defaults, so it sits at its parent. Writing one adds it. node.set_component(name, map)replaces a component, andnode.patch_component(name, map)changes the keys it names.node.transform.global_position(),global_rotation_euler()andglobal_scale()answer in world space.
Script files as modules
// scripts/util.bs
pub fn clamp(v: float, lo: float, hi: float) -> float {
if v < lo { lo } else if v > hi { hi } else { v }
}
// scripts/runner.bs
use util;
pub class Runner {
node: Node,
speed: float,
}
impl Runner {
fn update(dt: float) {
self.speed = util::clamp(self.speed + dt, 0.0, 10.0);
}
}
use util;linksutil.bsfrom beside the file, or from a folder above it.use a::b;linksa/b.bs.- Its
pubitems areutil::name. An item, field or method with no mark belongs to its file. internalopens one to its package:addons/<name>,deps/<alias>, or else the project.pubopens one to every file.- Files may use each other in a circle.
- Saving a module reloads every script that uses it.
Errors
A compile error names the file, line and column:
scripts/spinner.bs:14:27: error: cannot combine bool and int
- A failing engine call ends the script's call and logs the error.
- An index out of range or a division by zero traps. The call ends with the line in the log, and the instance runs its next call as before.
- A file's module grows to 256 MiB at most. An allocation past that traps.
Logs
log::info, log::warn and log::error write a line. The engine keeps
the last 500 in memory, and the Output dock shows them. log::print writes to
standard output as it stands.
Each run also writes its log to logs/run.log in the game's user data
folder, and keeps the last five runs as run.1.log and on. [log] to_file
turns it off and [log] keep sets how many runs stay. A panic is written
there before the process dies. A browser keeps the file in the page's
storage, so the next visit can read the run that crashed.
On Android the user data folder is in the app's internal storage, and every
line also goes to logcat under the tag balaur: adb logcat -s balaur.
log::since(cursor) answers each line once, for a script that sends the
log somewhere:
let read = log::since(self.cursor);
for entry in read.entries {
send(entry.level, entry.message);
}
self.cursor = read.cursor;
read.missed counts the lines dropped before they were read.
Tooling
script::check, complete, hover, signature, definition, symbols,
references, rename and format answer from the running engine. Two
clients read them: the editor's Script workspace, and balaur lsp, a Language
Server Protocol server on stdin and stdout.

| After the caret | What completes |
|---|---|
physics2d:: |
that module's functions and constants, each with the line the reference prints |
self.node.body2d. |
that component's properties and operations |
self. |
the script's fields and methods |
a string, a list or an any, then . |
that type's methods |
| anything else | this file's functions, structs and locals, the modules, keywords |
| Key | What it does |
|---|---|
⌘B |
Go to definition: locals, fields, methods, functions and structs |
⌥⇧F |
Format the buffer |
⌘⇧R |
Rename an identifier in the file |
⌘⇧F |
Replace text |
Ctrl works in place of ⌘ in every chord here.
A rename matches the name as a token, inside {..} interpolations too, and
skips string text and comments. Both rename and replace list every match
before writing.
balaur fmt . # lay every script out
balaur fmt . --check # name the files that would change; exits 1 if any do
The formatter keeps the author's line breaks and comments, indents each line by the brackets above it, and keeps one blank line of a run. It changes no token.
balaur lsp <project> serves diagnostics, completion, hover, signature help,
go-to-definition, document symbols, references, rename and formatting. The
engine repository ships a VS Code extension in editors/code; its README has
the Neovim and Zed recipes.
Events
The engine calls methods a script declares by name.
on_animation_finished(name)from an animation,on_clickfrom a widget,on_websocket_event(e)from a socket.- Most events have a polling twin, such as
input::key_just_pressed. An event is a frame-scoped snapshot.
init and an event handler may be async. One suspends on task::wait and
resumes at the start of the tick the result enters the simulation. update
and fixed_update never await. See Networking for the
delivery model.
pub class Fetch {
node: Node,
}
impl Fetch {
pub async fn init() {
let r = await task::wait(http::request("https://example.com"));
log::info("{r["status"]} {r["body"]}");
}
}
await task::seconds(t)andawait task::frames(n)count simulation time.task::wait(token)resolves to what the token was woken with, as anany.- A task does not survive a reload. The reload ends it and logs a warning.
Two ways for scripts to reach each other:
| Shape | Call |
|---|---|
| One target, by node handle | node.call("method", args...), up to four arguments |
| A named event from an emitter to its subscribers | events |
pub class Tower {
node: Node,
enemy: Node,
}
impl Tower {
fn init() {
self.enemy = scene::root().get_node("World/Enemy");
events::listen(self.node, "hit", self.enemy); // only that enemy's
events::listen(self.node, "hit"); // every emitter's
self.node.emit("hit", { "damage": 3 }); // from this node
}
pub fn on_hit(payload: any) {} // on_<name>, whichever it was
}
- Delivery is at the top of the next frame's update, in emission then subscription order.
- The emitter is part of the key. Delivery is a lookup.
events::emitis the same without an emitter.
Hot reload
- The host watches the project directory and recompiles a file on save.
- Every instance carries each field that kept its name and type. A field the new code adds starts at its default.
- A reload takes 2.3 ms on wasmtime and 0.17 ms on wasmi.
- A save that does not compile puts the diagnostic (file, line, column) in the Output dock. The previous code keeps running.
- Every engine call is checked at compile time. A misspelled one is caught on save.

Debugging
Click a line number in the Script workspace to set a breakpoint and run the scene. The Debugger dock shows the call stack and each frame's variables.
| Control | Key |
|---|---|
| Continue | F5 |
| Step over, into, out | F10, F11, Shift+F11 |
The same controls are the debugger module:
debugger::set_breakpoints("scripts/ball.bs", [12, 30]);
let pause = debugger::stop_location(); // nil, or the pause: reason, line, frames
debugger::resume(debugger::STEP_OVER); // CONTINUE, STEP_OVER, STEP_INTO, STEP_OUT
debugger::set_break_on_error(true);
- A file with a breakpoint is rebuilt with probes and runs on wasmi, which can hold a call at a line. The frame loop keeps drawing while it waits.
- An
asyncmethod stops at a breakpoint too, and goes back to waiting at its nextawait. - Numbers and bools changed at a stop are read back into the script.
- Break on error stops at the line that trapped, with each frame's variables as they were. An error pause is dismissed, not resumed.
Where it runs
Time against the same code in Rust, on macOS:
| Target | Engine | Particles | fib(25) |
|---|---|---|---|
| iOS | native code, compiled at export | 1.1x | 1.3x |
| Desktop, Android | wasmtime | 2.3x | 1.6x |
| A file under the debugger | wasmi | 16x | 11x |
In a browser the page's own engine runs them at 1.1x and 1.0x Rust compiled to WebAssembly.
- wasmtime keeps what it compiled in the game's data folder. A cached file loads in 0.84 ms.
- An iOS export translates the scripts to C and builds them with Xcode's
clang into
BalaurScripts.framework. - Floats come out bit for bit the same on every engine.
Determinism in scripts
math(math::sin,math::pow,math::PI, …) islibm-backed and bit-identical everywhere.randomis the engine's one seeded stream. A replay reproduces every draw.- Integers wrap on overflow.
- Simulation goes in
fixed_update. See Determinism for the rules.