Files
bworld/docs/modding/datastorage/index.md
T
2026-11-14 12:18:41 -03:00

45 lines
2.0 KiB
Markdown

# Saving Data
The server phase has no file access, so everything a mod keeps goes through the world, and is saved with it. Pick the
place by what the data belongs to:
| Data belongs to | Keep it in | Sent to players |
| ---------------------------- | ---------------------------------------------------- | ----------------------- |
| one block | its [tile data](../blocks/tiledata.md), `block.data` | never |
| one block, small and visible | a [block state](../blocks/states.md) | yes |
| a set of items | a [container](../inventories/containers.md) | while a screen shows it |
| one item stack | the stack's `data` | with the stack |
| the whole mod | `ctx.storage` | never |
Everything here must be plain JSON: objects, arrays, strings, numbers, booleans and `null`. No classes, `Map`s or
functions.
## Mod Storage
`ctx.storage` is a small key value store for each mod, saved with the world:
```ts
interface ModStorage {
get<T>(key: string): T | undefined;
set(key: string, value: unknown): void; // JSON values only
delete(key: string): void;
}
```
```ts
const count = ctx.storage.get<number>("smelted") ?? 0;
ctx.storage.set("smelted", count + 1);
```
Each mod has its own, so keys don't clash between mods. It's for things like totals and settings changed in game.
Settings a server picks before it starts belong in the mod's [config](../misc/config.md), and data about one block
belongs in that block's tile data, which goes away with the block.
## What Isn't Saved
- Variables in a script. Everything in memory is gone when the server restarts, so rebuild it in the server phase from
what was saved.
- [Timers](../misc/time.md#timers).
- Scripted [entities](../entities/index.md#behaviors), like the fishing hook.
- `get_lore` text, which is worked out each time a stack is sent.