dudeim
Member
- Joined
- Oct 5, 2007
- Messages
- 121
- Reaction score
- 9
Hey,
So I got this problem I have a table containing a metatable and well I want to serialize that table, but the built in function only works for non metatables.
These are the functions I'm talking about:
So is there anyway I can do this with metatables?
Thanks!
So I got this problem I have a table containing a metatable and well I want to serialize that table, but the built in function only works for non metatables.
These are the functions I'm talking about:
Lua:
function table.serialize(x, recur)
local t = type(x)
recur = recur or {}
if(t == nil) then
return "nil"
elseif(t == "string") then
return string.format("%q", x)
elseif(t == "number") then
return tostring(x)
elseif(t == "boolean") then
return x and "true" or "false"
elseif(getmetatable(x)) then --as you can see it doesn't accept tables (also if i remove this line i don't think it will work it isn't in here for no reason
error("Can not serialize a table that has a metatable associated with it.")
elseif(t == "table") then
if(table.find(recur, x)) then
error("Can not serialize recursive tables.")
end
table.append(recur, x)
local s = "{"
for k, v in pairs(x) do
s = s .. "[" .. table.serialize(k, recur) .. "]" .. " = " .. table.serialize(v, recur) .. ", "
end
return s:sub(0, s:len() - 2) .. "}"
end
error("Can not serialize value of type '" .. t .. "'.")
end
function table.unserialize(str)
return loadstring("return " .. str)()
end
Thanks!