Thomas
Thomas

Reputation: 491

Trying to deserialize and serialize a table in lua using the serpent library

So I am trying to do a simple serialization of a lua table, and deserialize it back into a table. But for some reason it just fails.

local a = {}
a[0] = {name="presetA"}
local line = serpent.line(a)

local presets, err = loadstring(line)

if (err) then
    log("Error")
    log(err)
else
    log("Success")
    log(serpent.block(presets))
end

After running, log(err) shows

[string "{[0] = {name = "presetA"}}"]:1: unexpected symbol near '{'

Upvotes: 0

Views: 922

Answers (1)

Piglet
Piglet

Reputation: 28958

loadstring loads a Lua chunk from the given string and runs it.

As your serialized table is not a valid Lua expression the interpreter reports the observed error.

Let's serialze an example:

serpent.line({key = "value"})

returns

"{key = "value"} --[[table: 0D80CF40]]"

A table constructor on it's own is not a valid Lua expression.

Try to run that line and you'll Lua will report:

input:1: unexpected symbol near '{'

The output of serpent.line cannot be used as input to loadstring.

Now see the difference if you use serpent.dump instead

"do local _={name="hallo"};return _;end"

This is a valid, executable Lua chunk that will return the serialized table.

Please note the following section from the serpent documentation:

Note that line and block functions return pretty-printed data structures and if you want to deserialize them, you need to add return before running them through loadstring. For example: loadstring('return '..require('mobdebug').line("foo"))() == "foo".

While you can use loadstring or load functions to load serialized fragments, Serpent also provides load function that adds safety checks and reports an error if there is any executable code in the fragment...

Please read manuals.

Upvotes: 4

Related Questions