In Lua so called tables are used as general data containers. They can be used to mimic or replace dictionary, arrays and classes from other programming languages. See the general Lua introduction for more on how tables work.
Since tables are ubiquitous in Lua code it makes sense to also use them to leverage persistent storage functionaliy. Furthermore, having various tables that are stored in different places can be used to control where data is stored. For example we could save some data game wide (e.g. global settings) and some data only in the currently opened city.
The aforementioned storage tables can be retrieved by various API functions dependent on the context the table will be stored in:
A single table that is stored globally for the game. So you could put things in here that should not be city dependent.
Is saved within the city file, so it's useful to save city dependent stuff in it.
- getBuildingStorage(x, y)
This table will be stored in the building specified by coordinates x, y. If the building get removed or replaced the data will get lost.
- getRoadStorage(x, y, level)
This table will be stored in the road specified by coordinates x, y and level. If the building gets removed or replaced the data will get lost.
All in all storing the value 42 in a x field within a personal storage table into a city would now look like this:
-- Let's use a unique, own key for the table that we will create within a storage table local key = script:getDraft():getId() -- Let's get our personal storage table within the city storage table (will be created if it doesn't exist) local tbl = Util.optStorage(City.getStorage(), key) -- Let's put something into it; this should still be there after saving the city, ending the game, and then coming back tbl.x = 42 -- Some moments later... print(tbl.x)
The way these storage tables are actually stored depends on the context. City dependent storage tables will be stored within the city file, while global storage tables will be part of the TheoTown settings.
There is no explicit save function for storage tables as they will be persisted automatically. In case a user exits a city without saving his changes the changes to city dependent storage tables will also not be saved.
Note that for technical reasons only tables and primitive values (string, numbers, booleans and nil) within a storage table will actually be stored persistently. However, you can put tables into tables and so on.
This was first documented here.