mirror of
https://github.com/TangentFoxy/lume.git
synced 2024-11-19 07:04:24 +00:00
Lots of tweaks to lume.serialize(); circular reference detection
This commit is contained in:
parent
7412706277
commit
688de3368e
35
lume.lua
35
lume.lua
@ -536,19 +536,36 @@ function lume.lambda(str)
|
|||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
function lume.serialize(x)
|
local serialize
|
||||||
local f = { string = function(v) return string.format("%q", v) end,
|
|
||||||
number = tostring, boolean = tostring }
|
local serializemap = {
|
||||||
f.table = function(t)
|
[ "number" ] = tostring,
|
||||||
|
[ "boolean" ] = tostring,
|
||||||
|
[ "nil" ] = tostring,
|
||||||
|
[ "string" ] = function(v) return string.format("%q", v) end,
|
||||||
|
[ "table" ] = function(t, stk)
|
||||||
|
stk = stk or {}
|
||||||
|
if stk[t] then error("circular reference") end
|
||||||
local rtn = {}
|
local rtn = {}
|
||||||
|
stk[t] = true
|
||||||
for k, v in pairs(t) do
|
for k, v in pairs(t) do
|
||||||
rtn[#rtn + 1] = "[" .. f[type(k)](k) .. "]=" .. f[type(v)](v) .. ","
|
rtn[#rtn + 1] = "[" .. serialize(k, stk) .. "]=" .. serialize(v, stk)
|
||||||
end
|
end
|
||||||
return "{" .. table.concat(rtn) .. "}"
|
stk[t] = nil
|
||||||
|
return "{" .. table.concat(rtn, ",") .. "}"
|
||||||
end
|
end
|
||||||
local err = function(t,k) error("unsupported serialize type: " .. k) end
|
}
|
||||||
setmetatable(f, { __index = err })
|
|
||||||
return f[type(x)](x)
|
setmetatable(serializemap, {
|
||||||
|
__index = function(t, k) error("unsupported serialize type: " .. k) end
|
||||||
|
})
|
||||||
|
|
||||||
|
serialize = function(x, stk)
|
||||||
|
return serializemap[type(x)](x, stk)
|
||||||
|
end
|
||||||
|
|
||||||
|
function lume.serialize(x)
|
||||||
|
return serialize(x)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user