Lua Serializing Tables
Serializing a table means turning it into a string that can be stored or sent. Loading that string back rebuilds a table with the same values.
An array becomes one string
table.concat joins array values with a separator. Braces around the result make a table literal string.
local scores = {10, 20, 30}
local text = "{" .. table.concat(scores, ", ") .. "}"
print(text)Load rebuilds the array
Adding return turns the literal into a chunk. Calling the loaded chunk returns the rebuilt table.
local text = "{10, 20, 30}"
local rebuilt = load("return " .. text)()
print(rebuilt[1], rebuilt[2], rebuilt[3])Named fields round trip too
string.format writes each field in table literal form. The loaded table then holds the same name and age.
local person = {name = "Sam", age = 14}
local text = string.format("{name = %q, age = %d}", person.name, person.age)
local rebuilt = load("return " .. text)()
print(rebuilt.name, rebuilt.age)Example
local items = {
{name = "pen", qty = 3},
{name = "book", qty = 2},
}
local text = "{"
for i = 1, #items do
text = text .. string.format("{name = %q, qty = %d},", items[i].name, items[i].qty)
end
text = text .. "}"
local rebuilt = load("return " .. text)()
for i = 1, #rebuilt do
print(rebuilt[i].name, rebuilt[i].qty)
end
print(#rebuilt)Key points
- Serialization: serialization is the act of turning a table into a string form.
- Round trip: a round trip is a serialize step followed by a load step that rebuilds the table.
- Load: load turns a string of Lua code into a function you can call.
- Return chunk: the string must start with return so calling the loaded function gives back the table.
- Equality check: round trip equality is proved by comparing printed fields, not by printing the tables themselves.
In this example, two item tables are turned into one literal string by a loop. load then rebuilds the list from that string. The final loop prints each rebuilt name and count, and the last line prints the rebuilt length.
Note
load runs code, so only load strings your own program built.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does the serialized string start with return when it is loaded?