# state

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 saving progress, keeping script state, recording a playthrough, restoring snapshots or checking replay determinism.

| In a script | Does |
| --- | --- |
| `state` | The script's own table. It survives a reload and is saved with the world; see below |
| `keeps_things({ "path", ... })` | Says which numbers the script keeps in `state` are things, at its top level: each a path of keys with a dot between, `*` for any key (`keeps_things { "hero", "bits.*.e" }`). A test of a change (`copy.land`, `change.test`) then holds such a number to the same thing, by name, however a thing added to the scene moved it, and any other kept number to the same number. Keeps nothing and moves no checksum. Called anywhere else, it is an error |
| `function on_restore()` | Defined by the script, if it keeps a cache. Called before it next runs when the game was put back to another moment; see `state` |
| `save.get("slot")`, `save.set("slot", table)`, `save.delete("slot")`, `save.slots()` | What a game keeps between runs |

### `state`

`state` is where a script keeps what must outlive a step and is not a component:
counters, timers, a list of entities. At the end of every step the host copies it into
the world, so it is part of every snapshot
and of the checksum, a protocol client can read it (`script.state`), and a world that
is rolled back hands the script its old `state` again before the next step.

What a game is belongs in the world or in `state`, and nowhere else. A `local` at the
top of a script is a cache: it is not saved, not in the checksum, and empty again after
a reload, so keep there only what can be built again from the world and `state` (a
lookup table, a list of entities found with `each`), and build it in `on_scene` or when
it is first needed. `state` costs every step for what it holds: the engine walks it at
the end of each step to keep the world's copy exact (about 50 ns an entry on a fast
desktop), so a big table that never changes, such as the handles of 900 pieces laid once,
is cheaper in such a `local`, built again in `on_scene` and `on_restore`.

When the game is put back to another moment (`game.restore`, `game.try`, a seek, a
rollback) `state` comes back as it was then, its tables new ones, and such a `local`
still holds what it had in the future the game came back from. A script that defines
`on_restore()` has it called once, before it next runs, after every such put back (and
after a reload that failed and put `state` back): empty its caches there (`cache = nil`,
`table.clear(seen)`) and they are built again when next needed. It must change nothing
of the game, only what a `local` keeps; `frost test --restore` finds one that does. A
`local` that `on_restore` empties is a cache to `frost check`, which does not warn of it.

So `state` holds only what can be stored: numbers, strings, true and false, and tables
of those with numbers or strings as keys. Anything else is refused at the end of the
step that put it there, with the error `E0307` naming the place: a
function, a coroutine, a buffer, a vector, a table with a metatable, a table that
holds itself or nests deeper than 32, a string that is not UTF-8. A table reachable by
two paths is stored once for each.

Read as JSON (`script.state`, `frost run --state`), a table with keys 1 to n is a list
and any other table an object; a table with nothing in it is always `{}`, never `[]`,
so a reader of a list that may be empty accepts both. An entity kept in `state` is its
number: `generation * 4294967296 + index`, where the protocol writes the same entity
`eINDEX.GENERATION` (`4294967299` is `e3.1`). It is always a whole number below 2^53,
so JSON and every language that reads it keep it exactly.

### Saves

`save.set("profile", { best = 120 })` replaces a slot's table, kept between runs;
`save.get("profile")` returns a copy or nil; `save.delete` empties a slot;
`save.slots()` lists the names. A save holds numbers, strings, true and false,
and tables of those, gaps too (`{ [3] = 41.5 }`); a number key is whole. A component's
number is a 32-bit float: 0.4 saves as 0.4000000059604645. A slot's name is a to z,
digits, `-` and `_`; a slot is at most 64 KB as TOML, a game at most 32 slots.

A shipped game keeps its slots in the player's data folder, or a browser's
`localStorage`, under the project's `id`; `frost dev`, in `saves/` by the project. A
changed slot is written once, after its step. Saves are input, not in the world or the
checksum: `frost run`, `frost test`, `frost check` and replays start from the `saves` their
recording declares, or none, and write nothing. Read a save in `on_scene`: a script's
top runs again on a reload.

```toml
# Optional: the frames the game is judged by. Each is the picture after `step` fixed
# steps of the recorded input, kept as `shots/NAME.png` beside this file; a name is
# letters, digits, `-` and `_`. `frost check --shots` takes them again and says which
# changed. `frost test --write` takes a shot's first picture when none is kept; a kept
# one only `frost check --shots --write-shots` writes over. With `overlay = "physics"` a shot has every collider, joint and contact
# drawn over it (as `frame.capture` draws them): a picture of what collides.
shots = [{ name = "title", step = 60 }, { name = "mid-level", step = 1960 }]
# Optional: what the recorded game comes to. `frost test` plays the recording for `steps`
# steps and requires this checksum: 16 hex digits that sum the whole run, the world
# before the first step and after every one. `frost test --write` writes it, and beside
# it `checkpoints`: the same sum at every 256th step and at each step a scene started,
# so a test that fails says between which two the game first went another way. Write
# neither by hand. With no `checkpoints`, `checksum` is the world's own after the last
# step, as `frost run` prints it: all an older project says, and all it is held to.
# Left out: the game has no recorded run, and `frost test` says so (`no recorded run`,
# `state: "no_replay"` with `--json`): it has not passed, and nothing failed.
replay = { steps = 3509, checksum = "89573f90dd5c32f7" }
checkpoints = [[256, "0f5c1d2e3a4b5c6d"], [512, "7e8f9a0b1c2d3e4f"]]
```

```toml
[input]
actions = ["move_x", "jump"]   # the names scripts read input by
players = 2                    # how many players have input, 1 to 16. Left out: 1
# Optional recorded input. Each stretch lasts `steps` fixed steps and holds the listed
# actions at the given values, from -1 to 1; an action left out is at rest (0).
# `player` says whose input it is; left out, player 0. Each player's stretches are
# played in the order written, one after another, from step 0, alongside the other
# players'. After a player's last stretch that player's actions are at rest.
# To replay binding hints, player = { id = 0, device = "pad" } selects pad labels;
# a numeric or omitted player selects keyboard labels. The last device stays held.
# `input.history` returns a played session in exactly this form.
recording = [
    { steps = 20 },
    { steps = 55, move_x = 1.0 },
    { steps = 2, move_x = 1.0, jump = 1.0 },
    { player = 1, steps = 77, move_x = -1.0 },
]
# Optional: the saves the recording starts from, each slot with its table.
saves = { profile = { best = 120 } }
# Optional: the frame the recording was made in, when that is not `[window] size` (a game
# that fills, played on a phone): it is replayed in that frame, and `input.history` writes
# it. Left out: `[window] size`.
frame = [1060, 540]
# Or the name of a file that holds those keys and nothing else, as `input.history`
# returns it: recording = "run.toml". It is read when the game is first stepped on
# its recording (`frost run`, a test) and by `frost check`; a window or a web page plays
# live input and never reads it, and an export does not copy it.
```
