Skip to content

Persistent variables

Persistent variables allow you to store data that survives script restarts and world save/load. They are useful for keeping state between sessions, such as counters, configuration values, or custom train data.

The pv global provides a simple and efficient interface for interacting with persistent data. Any values stored in pv are saved across script executions and world save and loads. Below is a detailed breakdown of how to use the pv global.

Storing persistent data

You can store data in pv just like you would with a regular Lua table.

pv.number = 42
pv.title = 'Traintastic is awesome!'
pv.very_cool = true

pv['freight_car_1'] = {
  cargo = 'grain',
  destination = 'upper yard'
}

Note

Persistent variables supports storing booleans, numbers, strings, tables, enums, sets, objects and object methods.

Retrieving persistent data

To retrieve a previously stored value, including tables, access the corresponding key in the pv global:

log.debug(pv.number)
log.debug(pv.title)
log.debug(pv.very_cool)

log.debug(pv.freight_car_1.cargo)

for k, v in pairs(pv['freight_car_1']) do
  log.debug(k, v)
end

Deleting persistent data

To delete a stored persistent value, including tables, simply assign nil to the desired key:

pv.number = nil
pv.title = nil
pv.very_cool = nil
pv.freight_car_1 = nil

Checking if data exists

To determine if a persistent variable has been set, use a nil checks. This pattern is useful for initializing default values or handling cases where the persistent variables are cleared.

if pv.freight_car_1 == nil then
  pv.freight_car_1 = {
    cargo = 'none',
    destination = 'unset'
  }
end