1
0
mirror of https://github.com/20kdc/OC-KittenOS.git synced 2024-11-09 12:08:08 +11:00
OC-KittenOS/code/libs/serial.lua

42 lines
907 B
Lua
Raw Normal View History

-- 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
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
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
return tostring(s)
end
2018-03-28 00:40:05 +11:00
if s == nil then
return "nil"
end
error("Cannot serialize " .. type(s))
end
return {
serialize = function (x) return "return " .. doSerialize(x) end,
deserialize = function (s)
local r1, r2 = pcall(function()
return load(s, "=serial", "t", {})()
end)
if r1 then
return r2
else
return nil, tostring(r2)
end
end
}