Home  Contents

table.tostring

Table Core4 Lua Commands

SYNOPSIS

  1. str = table.tostring(tbl[, indent])
  2. tbl = table.fromstring(str)

DESCRIPTION

table.tostring() recursively encodes the contents of tbl back into Lua sourcecode. The returned string can be given to the lua compiler which will compile it back into the same table.

Table keys must be numbers or strings, table values must be numbers, strings, tables or values that implement the "__undump" metamethod. All other items will silently be discarded. Currently, only the Date/Time instances support undump.

indent specifies indentation of the result:

-2 All unnecessary whitespace is left out. Hard to read, but space efficient.
-1 Result is returned as a single line with a few helpful spaces (Default).
>=0 Each item is printed on a separate line, indented by the given number of spaces. Nested tables will indent further in multiples of this value.

table.fromstring() is the reverse of the above, turning a string back into a table. This function returns nil, should the conversion fail. The string is actually fed to the Lua compiler for conversion.

NOTES

If any value being converted by table.tostring() has an "__undump" metamethod, that metamethod is called with the value. The "__undump" metamethod must return a string that is a source code representation of the value, or nil if this is not possible. Any error that happens while calling "__undump" is discarded and counts as if nil was returned.

EXAMPLE

print(table.tostring( { foo = "abcdef", bar = 5, blubb = { "A",2,3,4 }, nix = {} } ))
{ blubb={ "A", 2, 3, 4 }, foo="abcdef", bar=5, nix={} }
print(table.tostring( { foo = "abcdef", bar = 5, blubb = { "A",2,3,4 }, nix = {} }, nil, "test" ))
test={ blubb={ "A", 2, 3, 4 }, foo="abcdef", bar=5, nix={} }
print(table.tostring( { foo = "abcdef", bar = 5, blubb = { "A",2,3,4 }, nix = {} }, 2 ))
{ blubb = { "A", 2, 3, 4 }, foo = "abcdef", bar = 5, nix = {} }

These functions are often used to save configuration data into a file where it can be loaded back later. A simple set of functions that save and restore a table could look like this:

#include <lua/fcntl.h> function save_table(filename, data) local fh = rawio.open(filename, O_WRONLY | O_CREAT) if (not fh) then return nil end fh:write(table.save(data)) fh:close() return true end function restore_table(filename) local fh = rawio.open(filename, O_RDONLY) if (not fh) then return nil end local str = fh:read(65536) -- Note: Sensible limit fh:close() return table.fromstring(str) end

SEE ALSO