Skip to content

Instantly share code, notes, and snippets.

@dansouza
Created September 20, 2012 17:19
Show Gist options
  • Save dansouza/3757165 to your computer and use it in GitHub Desktop.
Save dansouza/3757165 to your computer and use it in GitHub Desktop.
Lua prettyprinter
#!/usr/bin/env lua
-- works like PHP's print_r(), returning the output instead of printing it to STDOUT
function prettyprint(data)
-- cache of tables already printed, to avoid infinite recursive loops
local tablecache = {}
local buffer = ""
local padder = " "
local inited = 0
local function _prettyprint(d, depth)
local t = type(d)
local str = tostring(d)
local items = 0
if (t == "table") then
if (tablecache[str]) then
-- table already dumped before, so we dont
-- dump it again, just mention it
buffer = buffer.."<"..str..">"
else
tablecache[str] = (tablecache[str] or 0) + 1
items = 0
for k, v in pairs(d) do items = items + 1 end
buffer = buffer.."("..str.." n="..items..") {"
items = 0
for k, v in pairs(d) do
if (items == 0) then
buffer = buffer .. "\n"
end
items = items + 1
if (type(k) == "string") then
k = '"' .. k .. '"'
end
buffer = buffer..string.rep(padder, depth+1).."["..k.."] => "
_prettyprint(v, depth+1)
end
if (items > 0) then
buffer = buffer..string.rep(padder, depth).."}"
else
buffer = buffer.."}"
end
end
elseif (t == "number") then
buffer = buffer.."("..t..") "..str..""
else
buffer = buffer.."("..t..") \""..str.."\""
end
if (depth > 0) then
buffer = buffer .. "\n"
end
end
_prettyprint(data, 0)
return buffer
end
--[[
print(prettyprint({
[1] = "this is the first element",
[2] = "and this is the second",
[3] = 3,
[4] = 3.1415,
["nested"] = {
["lua"] = "is cool but",
["luajit"] = "is fucking awesome!",
["even_for"] = {"almost", "empty", {}},
},
["some-files"] = {
[0] = io.stdin,
[1] = io.stdout,
[2] = io.stderr
}
}))
-- outputs:
(table: 0x40e16320 n=6) {
[1] => (string) "this is the first element"
[2] => (string) "and this is the second"
[3] => (number) 3
[4] => (number) 3.1415
["nested"] => (table: 0x40e16370 n=3) {
["lua"] => (string) "is cool but"
["luajit"] => (string) "is fucking awesome!"
["even_for"] => (table: 0x40e163d0 n=3) {
[1] => (string) "almost"
[2] => (string) "empty"
[3] => (table: 0x40e16410 n=0) {}
}
}
["some-files"] => (table: 0x40e0f010 n=3) {
[0] => (userdata) "file (0x3f1e79b6a0)"
[1] => (userdata) "file (0x3f1e79b780)"
[2] => (userdata) "file (0x3f1e79b860)"
}
}
]]
@hi-tech
Copy link

hi-tech commented Jul 30, 2015

Thanks for this version!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment