Next: 7.4 Inheritance Up: 7 Some Examples Previous: 7.2 Manipulating Strings

7.3 Persistence

Because of its reflexive facilities, persistence in Lua can be achieved with Lua. This section shows some ways to store and retrieve values in Lua, using a text file written in the language itself as the storage media.

To store a single value with a name, the following code is enough:

function store (name, value)
  write('\n' .. name .. '=')
  write_value(value)
end
function write_value (value)
  local t = type(value)
      if t == 'nil'    then write('nil')
  elseif t == 'number' then write(value)
  elseif t == 'string' then write('"' .. value .. '"')
  end
end
In order to restore this value, a lua_dofile suffices.

Storing tables is a little more complex. Assuming that the table is a tree, and all indices are identifiers (that is, the tables are being used as records), its value can be written directly with table constructors. First, the function write_value is changed to

function write_value (value)
  local t = type(value)
      if t == 'nil'    then write('nil')
  elseif t == 'number' then write(value)
  elseif t == 'string' then write('"' .. value .. '"')
  elseif t == 'table'  then write_record(value)
  end
end
The function write_record is:
function write_record(t)
  local i, v = next(t, nil)
  write('{')  -- starts constructor
  while i do
    store(i, v)
    write(', ')
    i, v = next(t, i)
  end
  write('}')  -- closes constructor
end

Next: 7.4 Inheritance Up: 7 Some Examples Previous: 7.2 Manipulating Strings