2018-03-19 10:10:54 +11:00
|
|
|
-- This is released into the public domain.
|
|
|
|
-- No warranty is provided, implied or otherwise.
|
|
|
|
local doSerialize = nil
|
|
|
|
function doSerialize(s)
|
|
|
|
if type(s) == "table" then
|
|
|
|
local str = "{\n"
|
2018-03-28 00:40:05 +11:00
|
|
|
local p = 1
|
2018-03-19 10:10:54 +11:00
|
|
|
for k, v in pairs(s) do
|
2018-03-28 00:40:05 +11:00
|
|
|
if k == p then
|
|
|
|
str = str .. doSerialize(v) .. ",\n"
|
|
|
|
p = p + 1
|
|
|
|
else
|
|
|
|
str = str .. "[" .. doSerialize(k) .. "]=" .. doSerialize(v) .. ",\n"
|
|
|
|
end
|
2018-03-19 10:10:54 +11:00
|
|
|
end
|
|
|
|
return str .. "}"
|
|
|
|
end
|
|
|
|
if type(s) == "string" then
|
|
|
|
return string.format("%q", s)
|
|
|
|
end
|
2018-03-28 00:40:05 +11:00
|
|
|
if type(s) == "number" or type(s) == "boolean" then
|
2018-03-19 10:10:54 +11:00
|
|
|
return tostring(s)
|
|
|
|
end
|
2018-03-28 00:40:05 +11:00
|
|
|
if s == nil then
|
|
|
|
return "nil"
|
|
|
|
end
|
2018-03-19 10:10:54 +11:00
|
|
|
error("Cannot serialize " .. type(s))
|
|
|
|
end
|
2018-04-07 06:05:47 +10:00
|
|
|
return {
|
2018-03-19 10:10:54 +11:00
|
|
|
serialize = function (x) return "return " .. doSerialize(x) end,
|
|
|
|
deserialize = function (s)
|
2018-04-07 06:05:47 +10:00
|
|
|
local r1, r2 = pcall(function()
|
|
|
|
return load(s, "=serial", "t", {})()
|
|
|
|
end)
|
2018-03-19 10:10:54 +11:00
|
|
|
if r1 then
|
|
|
|
return r2
|
2018-04-07 06:05:47 +10:00
|
|
|
else
|
|
|
|
return nil, tostring(r2)
|
2018-03-19 10:10:54 +11:00
|
|
|
end
|
|
|
|
end
|
2018-04-07 06:05:47 +10:00
|
|
|
}
|