Skip to content

sf2.state

Mod state is data that your mod keeps and the game saves with the profile. Register a named value first, then read and change it. Get sf2 with local sf2 = require("sf2").

Define the names, types, defaults and version of your saved data.

Signature: sf2.state.register { version, fields?, aliases?, tombstones?, migrations? }

Parameters

Parameter Type Required
definition StateDefinition Required

Fields of StateDefinition

Field Type Required Meaning
version integer Required —
fields table<string,FieldSchema|number|boolean|string> Optional A default value, or { type, default?, required? }.
aliases table<string,string> Optional —
tombstones string[] Optional —
migrations table<integer,fun(old:table<string,any>):table<string,any>|nil> Optional —

Returns: nil.

When: Entrypoint, once.

sf2.state.register {
version = 1,
fields = {
victories = 0, -- integer, starts at 0
finished = false, -- boolean, starts false
nickname = { type = "string", required = false }, -- absent until set
},
}

A plain value is the starting value and gives the type (whole number = integer, other number = number, boolean, string). Use the long form { type, default?, required? } for a number that starts whole but holds fractions, or an optional field. A bare type word such as victories = "integer" is an error. Functions, nested tables and asset handles cannot be saved. Raise version when the saved shape changes and use aliases, tombstones and migrations to carry old saves forward; see saving and options.

Read one saved value belonging to this mod.

Signature: sf2.state.get(name)

Parameters

Parameter Type Required
name string Required

Returns: A number, boolean or string, or nil if absent. An undeclared name is an error.

When: After the profile has loaded.

local victories = sf2.state.get("victories")

Update one or more fields together; others keep their values.

Signature: sf2.state.set { field_name = value, ... }

Parameters

Parameter Type Required
values table<string,any> Required

Returns: nil.

When: After the profile has loaded.

sf2.state.set { victories = 3, finished = true }

An unknown field or wrong type rejects the whole batch. A nil value does not clear a field; use sf2.state.unset.

Outside a fight, the campaign is saved to disk within about a second of the write. During a fight, the write is saved with the fight’s result.

Remove a field’s value and apply its default, if any.

Signature: sf2.state.unset(name)

Parameters

Parameter Type Required
name string Required

Returns: nil.

When: After the profile has loaded.

sf2.state.unset("nickname")

A required field with no default cannot be cleared.