# scripts

Part of the [scripting reference](index.md), written by the engine so it matches your `frost`. Start with [your first game](../start/first-game.md) if you are new.

Use when writing Luau gameplay, spawning or finding entities, reading or changing fields, sharing libraries, loading data or switching scenes.

# Coldwave scripting reference

Everything a game's script can call, every component the engine draws or simulates, and every key of
the project file. A game is a project file, scenes and Luau scripts; `docs/first-game.md` walks through making one.
This page is written by `frost reference` from the engine's own text: do not edit it.

## Scripts

This list is the whole API. An entity is a number; keep it, compare it, use it as a key.
Every function but `print` needs the world, so it works inside `step` and not at the
top level of a script, which runs when the script is loaded.

| In a script | Does |
| --- | --- |
| `function step(dt)` | Defined by the script. Called once per fixed step; `dt` is the step in seconds |
| `find("name")` | The entity that has that name, from the scene file or from `spawn`, or nil when there is none |
| `get(entity, "Component", "field")` | Reads one field |
| `set(entity, "Component", "field", value)` | Writes one field. The value must match the field's type |
| `has(entity, "Component")` | Whether the entity has the component. False for one that is gone |
| `each("A", "B", ...)` | The entities that have every named component |
| `spawn("A", "B", ...)` | Creates an entity with the named components at their defaults |
| `spawn("A", { B = { field = value } })` | The same with values: a table gives components by name, each with the fields to set. Names and tables mix in any order |
| `spawn("A", { name = "boss" })` | The same with a name, which `find("boss")` and the protocol then find. A name a living entity has is an error (`E0006`) |
| `despawn(entity)` | Removes an entity; false if it was already gone |
| `math.random()`, `math.random(n)`, `math.random(m, n)` | Seeded random: 0 to 1, 1 to n, m to n |
| `scene.load("level2.toml")` | Replaces every entity with those of a scene, once this step is over. See below |
| `scene.name()` | The scene the game is in, as the project file names it |
| `tuning` | The project's `[tuning]` numbers: `tuning.jump` |
| `library("kit.luau")` | Runs a library of the project and returns what it returns. See below |
| `data("levels/one.toml")` | A data file of the project as a new plain table. See below |
| `print(...)` | Writes its values as one line to standard error. See below |

Kinds: give each kind of thing a game spawns a component of its own that says what it
is, even one with no fields (`Moth = {}` under `[components]`, then `spawn("Moth", ...)`),
and give a thing there is one of a name. `each("Moth")` then finds them, and editors group
a scene's entities by it.

`each(..., {"Transform.x", ...})` also requires the selected numeric fields' components
(`f32`, `f64`, `i32` or `u32`) and returns IDs, then one copied f64 buffer per field:
eight little-endian bytes per ID.
`set(ids, component, field, buffer)` writes one back in list order (duplicates too).
Dense lists; metatables ignored. Spawns stay out; dead IDs error, never write reused slots.
Length errors write nothing; entry errors keep earlier writes. Budget: one unit per field
and copied value. Example:
`local ids,xs=each("Transform",{"Transform.x"}); for i=1,#ids do local p=(i-1)*8; buffer.writef64(xs,p,buffer.readf64(xs,p)+dt) end; set(ids,"Transform","x",xs)`.

Numbers: Luau uses 64-bit floats. Field defaults select storage: `0.0` is f32
(`0.1` reads back as `0.10000000149011612`); `0` is signed i32;
`{ f64 = 0.0 }` keeps every double bit; `{ u32 = 0 }` holds 0..4294967295.
Integer fields refuse fractions and out-of-range values. Float storage preserves NaN
payloads; equality and checksums treat all NaNs alike, but distinguish signed zeros.
Scene text canonicalizes NaNs; JSON inspection returns null for nonfinite floats.
Tweens calculate in f32, including when targeting f64/u32.

### The language

Scripts are Luau, in a sandbox: besides the API above they have Luau's `table`, `string`,
`math`, `bit32`, `utf8`, `buffer`, `vector` and `coroutine` libraries and its basic
functions (`pairs`, `ipairs`, `type`, `tostring`, `tonumber`, `assert`, `error`, `pcall`,
`select`, `unpack`). There are no files, no clock, no network and no `require`: what a
script works with is the world, and the same scripts, world and inputs play the same on
every machine. `math.random` is the game's seeded source, not the machine's. All of
`math` gives the same bits on every machine and in a browser (its trigonometry, `exp`,
`log` and `pow` are the engine's own): turn and aim with it freely. One thing is the
machine's: the `^` operator with a power other than a written `2`, `3` or `0.5`. Use
`math.pow(x, y)` for those. Two are the engine's additions, for code ported from C, C# or
JavaScript: `bit32.mul(a, b)`, the product of two 32-bit words, wrapped as C wraps it (a
plain `a * b` of two words passes 2^53 and drops low bits); and `math.roundeven(x)`, the
nearest whole number with halves to the even one (`math.round` takes them away from zero).

A script cannot hang or starve the game. One run of a script is stopped after a million
loop turns and function calls (`E0305`), and all scripts together may hold 64 MiB
(`E0306`). Both are counted, not timed, so they fall at the same point on every machine.
An error in `step` stops the game at that step with the script's name and line (`E0302`);
under `frost dev` the game waits, and goes on when the file is saved again.

### Scenes

`scene.load(name)` starts a scene: when the step in which it was called is over, every
entity is removed and the scene's own are made, as when the game started. The name is
the scene's path as the project file writes it: its `scene`, or one of its `scenes`.
Loading the scene the game is in starts it again, which is how a game restarts.
What several scenes share (a camera, a HUD) is written once, in a scene file the others
`include` (see the project file's `scenes`).

Only the entities change. Every script keeps its `state`, so a score or a level
number carries over, and a script that wants a clean start clears its own. An entity
number kept from before names nothing any more: look entities up again with `find`.
The rest of the step that called `scene.load` still runs in the old scene, and the
random source goes on from where it was. Then, still in that step, every script that
defines `on_scene(name)` has it called with the scene's name and the new entities in
place: spawn what the scene needs and set what it shows there, and no frame is drawn of
the scene as its file alone has it. A `scene.load` called from `on_scene` waits for the
end of the next step; while it waits it is in the checksum and a snapshot. The scene the game starts in gets the same call, once the game is
loaded and before its first step. A name that is no scene of the game fails the step
(`E0423`).

### Libraries

A library is a Luau file that scripts share. The
project lists it under `libraries`, and a script takes it in by the path written
there:

```lua
local kit = library("lib/kit.luau")
```

`library` reads no file while the game runs: the libraries were loaded with the game. The library's text is run and what it returns, usually
a table of functions, is the result. It is run again for every call, so each
script has its own copy and scripts share nothing through it; call it once, at the
top of a script. Two calls make two copies, in two scripts or in one (two libraries that
each take in a third): a table one copy makes is never `==` to one another makes, so
tell such tables apart by a field, not by which table they are. A library has no `state` and no `step` of its own: its functions use
the script API, and so work where the script that calls them could. A library may
take in another, by the name the project file writes, or from its own folder with `./`
or `../` (`library("./maths.luau")` in `lib/kit.luau` is `lib/maths.luau`), so a set of
libraries that take each other in works from any project that lists them. When a library
fails, the error names the script that was running, and the message starts with the
library's name and line.

### Data files

A data file is TOML that scripts read as a plain table: a level, a list of waves, a
course. The project lists it under `data`, and a script reads it by the path written
there, or from its own folder with `./` or `../`, as with `library`:

```lua
local level = data("levels/one.toml")   -- [[waves]] count = 3 ... is level.waves[1].count
```

A TOML table is a table with text keys, an array a list from 1, a string text, an
integer or a float a number and a boolean true or false. A date is refused, and so is
an integer past 2^53, which a number cannot hold exactly. Data files are read when the
game loads and never while it runs; each call returns a new table, so a script may
change its own. A run depends on its data as on its scripts: a changed data file starts
the game again, and a replay recorded with other data gives another checksum.

### `print`

`print` is for the author, not for the game: its output is not part of the simulation
and no command returns it. It goes to standard error, one line per call, values
separated by tabs: the terminal the program was started from (for an MCP client,
wherever it shows a server's error stream), or a browser's console. Standard output is
never written, because `frost serve` and `frost mcp` speak their protocol there.

### Warnings

`frost check` lists warnings: what is probably a mistake though nothing failed, like
`W0308`, a script with no global `step` function, which loads and never runs.
