dvcolgan
dvcolgan

Reputation: 7728

Serialize Lua table, including pure Lua functions?

We need to serialize a Lua table that includes strings, numbers, tables, and functions. There is code in the Programming Lua book to serialize tables that consist of strings, numbers, and tables. We tried to adapt this function to add the ability to serialize functions. Specifically, we added a case for type == 'function' and called string.dump on the function:

if type(o) == "number" then
    return tostring(o)
elseif type(o) == "function" then
    return "loadstring("..string.dump(o)..")"
else
    -- assume it is a string
    return string.format("%q", o)
end

This injected Lua bytecode into the rest of the plaintext table representation. That was the closest thing we could come up with.

We don't care if he serialized result is human-readable or not, it just has to be able to work like this:

mytable = [some complicated lua table with functions]
dump = dump_t(mytable)

...

loaded_table = load_t(dump)

Any ideas?

Upvotes: 2

Views: 4948

Answers (1)

Doug Currie
Doug Currie

Reputation: 41180

See the wiki page for a number of implementations.

Tony Finch's version might work for you.

Upvotes: 1

Related Questions