Skip to content

Instantly share code, notes, and snippets.

@ManuelBlanc
Created September 25, 2019 00:49
Show Gist options
  • Save ManuelBlanc/79714258508e672c9e51b814c82927da to your computer and use it in GitHub Desktop.
Save ManuelBlanc/79714258508e672c9e51b814c82927da to your computer and use it in GitHub Desktop.
local type, next, tostring = type, next, tostring
local byte, find, format, gsub, concat = string.byte, string.find, string.format, string.gsub, table.concat
local function ctlsub(c)
if c == "\t" then return "\\t"
elseif c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
else return byte(c) end
end
local function serialize_push(b, v, q)
local t = type(v)
if t == "table" then
if next(v) == nil then b[#b+1] = "{}" return end
if b[v] then b[#b+1] = '"table: loops_to#'..b[v]..'"' return end
b[v], b.l = b.l, b.l + 1
b[#b+1] = "{\n"
local i, qq = 1, q.." "
for k, w in next, v do
b[#b+1] = qq
if k ~= i then
if type(k) == "string" and find(k, "^[%a_][%w_]*$") then
b[#b+1] = k
b[#b+1] = " = "
else
b[#b+1] = "["
serialize_push(b, k, qq)
b[#b+1] = "] = "
end
else
i = i + 1
end
serialize_push(b, w, qq)
b[#b+1] = ",\n"
end
b[#b+1] = q.."}"
elseif t == "boolean" or t == "number" or t == "nil" then b[#b+1] = tostring(v)
else b[#b+1] = gsub(format("%q", tostring(v)), "%c", ctlsub)
end
end
local function serialize(v)
local b = {nil,nil,nil,nil,nil,nil,nil,nil,l=1}
serialize_push(b, v, "")
return concat(b)
end
print(serialize(_G))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment