Created
June 10, 2010 22:57
-
-
Save TheLinx/433755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- this goes in your LUA_PATH, which is usually: | |
-- /usr/share/lua/5.1/ | |
-- /usr/local/share/lua/5.1 | |
-- C:\Program Files\Lua\5.1 | |
-- first, require("printr") | |
-- then, use the function printr() | |
-- this code is public domain | |
local stringFormat,stringRep,stringChar = string.format,string.rep,string.char | |
local tableInsert,tableConcat = table.insert,table.concat | |
local function serializevalue(v, d, n) | |
local d = d or {} | |
local t = type(v) | |
if t == "string" then | |
v:gsub("\\\n", "\\n"):gsub("\r", "\\r"):gsub(stringChar(26), "\"..string.char(26)..\"") | |
return stringFormat("%q", v) | |
elseif t == "number" then | |
return stringFormat("%d", v) | |
elseif t == "boolean" then | |
return stringFormat("%s", tostring(v)) | |
elseif t == "table" then | |
if d[v] then | |
return "{...}" | |
end | |
d[v] = true | |
return stringFormat("%s", serializetable(v, d, n+1)) | |
else | |
return '"'..tostring(v)..'"' | |
end | |
end | |
function serializetable(table, d, n) | |
local s,n = {},n or 1 | |
tableInsert(s, "{\n") | |
for k,v in pairs(table) do | |
tableInsert(s, stringRep("\t", n)) | |
tableInsert(s, serializevalue(k, d, n).." = ") | |
tableInsert(s, serializevalue(v, d, n)) | |
tableInsert(s, ",\n") | |
end | |
if s[#s] == ",\n" then | |
s[#s] = "\n" | |
end | |
tableInsert(s, stringRep("\t", n-1)) | |
tableInsert(s, "}") | |
return tableConcat(s) | |
end | |
function printr(t) | |
return print(serializetable(t)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment