Skip to content
Snippets Groups Projects
Commit 6f43ddef authored by DarkGod's avatar DarkGod
Browse files

use faster serialization

parent 926f57fe
No related branches found
No related tags found
No related merge requests found
...@@ -83,38 +83,71 @@ end ...@@ -83,38 +83,71 @@ end
--- This is a really naive algorithm, it will not handle objects and such. --- This is a really naive algorithm, it will not handle objects and such.
-- Use only for small tables -- Use only for small tables
function table.serialize(src, sub, no_G, base) function table.serialize(src, sub, no_G, base)
local str = "" local chunks = {}
if sub then str = "{" end if sub then
chunks[1] = "{"
end
for k, e in pairs(src) do for k, e in pairs(src) do
local nk, ne = k, e local nk = nil
local nkC = {}
local tk, te = type(k), type(e) local tk, te = type(k), type(e)
if no_G then if no_G then
if tk == "table" then nk = "["..table.serialize(nk, true).."]" if tk == "table" then
elseif tk == "string" then -- nothing nkC[#nkC+1] = "["
else nk = "["..nk.."]" nkC[#nkC+1] = table.serialize(k, true)
nkC[#nkC+1] = "]"
elseif tk == "string" then
nkC[#nkC+1] = k
else
nkC[#nkC+1] = "["
nkC[#nkC+1] = tostring(k)
nkC[#nkC+1] = "]"
end end
else else
if tk == "table" then nk = "["..table.serialize(nk, true).."]" if not sub then
elseif tk == "string" then nk = string.format("[%q]", nk) nkC[#nkC+1] = (base and tostring(base) or "_G")
else nk = "["..nk.."]" end
nkC[#nkC+1] = "["
if tk == "table" then
nkC[#nkC+1] = table.serialize(k, true)
elseif tk == "string" then
-- escaped quotes matter
nkC[#nkC+1] = string.format("%q", k)
else
nkC[#nkC+1] = tostring(k)
end end
if not sub then nk = (base or "_G")..nk end nkC[#nkC+1] = "]"
end end
if te == "table" then nk = table.concat(nkC)
str = str..string.format("%s=%s ", nk, table.serialize(ne, true))
elseif te == "number" then -- These are the types of data we are willing to serialize
str = str..string.format("%s=%f ", nk, ne) if te == "table" or te == "string" or te == "number" or te == "boolean" then
elseif te == "string" then chunks[#chunks+1] = nk
str = str..string.format("%s=%q ", nk, ne) chunks[#chunks+1] = "="
elseif te == "boolean" then if te == "table" then
str = str..string.format("%s=%s ", nk, tostring(ne)) chunks[#chunks+1] = table.serialize(e, true)
elseif te == "number" then
-- float output matters
chunks[#chunks+1] = string.format("%f", e)
elseif te == "string" then
-- escaped quotes matter
chunks[#chunks+1] = string.format("%q", e)
else -- te == "boolean"
chunks[#chunks+1] = tostring(e)
end
chunks[#chunks+1] = " "
end
if sub then
chunks[#chunks+1] = ", "
end end
if sub then str = str..", " end
end end
if sub then str = str.."}" end if sub then
return str chunks[#chunks+1] = "}"
end
return table.concat(chunks)
end end
function string.unserialize(str) function string.unserialize(str)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment