Menu
Contents

Persistent variables

Persistent variables allow you to store and retrieve data that remains available across multiple executions of the Lua script. This can be particularly useful for maintaining state information that needs to be retained beyond the current script's lifetime.

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. Supported data types are numbers, strings, booleans, tables, enums, sets, objects and object methods.

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

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

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 for persistent data

To determine if a persistent variable has been set, use an if statement with nil checks. Variables in pv that haven't been initialized or have been deleted will return nil. 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