# Recipe: debug a script

Goal: find why a value is wrong. Start with the cheap questions; stop at a line only when
they do not answer. Examples use the basics sample,
where a coin worth 5 is picked up at step 131.

## 1. Does it load?

```sh
frost check game.toml
```

Each problem is `FILE:LINE: CODE: what and the fix`. Fix those first.

## 2. Who wrote the value?

```sh
frost blame game.toml score.Text.text
```

```text
score.Text.text is "SCORE 5" at step 180
  script main.luau:24 in step: step 131, 1 write, from "SCORE 0"
```

Add `--step N` to ask at another step and `--history 4` for earlier writers. Ask about a
pixel with `--pixel X,Y`. Over the protocol: `blame.on`, then `blame.value {entity,
component, field}`.

## 3. Stop at the line

Over the protocol (or `frost dap` from an editor, which drives the same commands):

```json
{"method":"debug.attach","params":{}}
{"method":"debug.breakpoints","params":{"file":"main.luau","lines":[23]}}
{"method":"input.set","params":{"player":0,"action":"move_x","value":1}}
{"method":"game.step","params":{"steps":300}}
```

`game.step` returns at once when a script stops: `"stopped": {"file": "main.luau",
"line": 23, "reason": "breakpoint"}` at step 101. Then:

| Ask | With |
| --- | --- |
| Where am I | `debug.stack` |
| What is in scope | `debug.scope {frame: 0}`, and `debug.expand` to open a table |
| What is this | `debug.evaluate {text: "picked.value"}` -> `5` |
| One line on | `debug.step {kind: "over"}` (or `"into"`, `"out"`) |
| Go on | `debug.continue`; `debug.detach` when done |

`debug.stack`, `scope`, `expand`, `evaluate`, `step` and `continue` need a stopped
script (`E0442` otherwise); `debug.state` says whether one is.

## 4. Make it happen again

The recording replays the bug at the same step every time: `game.seek {step: 131}` puts
the game there, and `game.try {from, inputs}` plays a branch of input from a snapshot in
one call, to test a guess without changing files.

## Checks

```sh
frost check game.toml
frost test game.toml            # the fix holds the recorded run (or fails where meant)
frost test --restore game.toml  # nothing kept in a local that should be in state
```

When the fix changes the run on purpose, look at a shot, then `frost test --write`.

More: [debugging](../../guides/debugging.md), `frost dap --help`, `frost help blame`.
