Skip to content

Instantly share code, notes, and snippets.

@Nexuapex Nexuapex/dump.lua
Created Jun 17, 2012

Embed
What would you like to do?
Dumping a description of a Lua value
local dump_table_threshold = 3
local dump_indent = (" "):rep(4)
local dumptable = {
["nil"] = tostring,
["number"] = tostring,
["string"] = function(value) return "\"" .. value .. "\"" end,
["boolean"] = tostring,
["table"] = function(value, depth, markers)
if markers[value] then
return "recursively-referenced table"
end
markers[value] = true
local lines = setmetatable({}, {__index = table})
local indices = {}
local long = false
for i, v in ipairs(value) do
local vstr, l = dumpstr(v, depth + 1, markers)
lines:insert(vstr)
indices[i] = true
long = long or l
end
for k, v in pairs(value) do
if not indices[k] then
local kstr, l1 = dumpstr(k, depth + 1, markers)
local vstr, l2 = dumpstr(v, depth + 1, markers)
lines:insert("[" .. kstr .. "] = " .. vstr)
long = long or l1 or l2
end
end
long = long or (#lines > dump_table_threshold)
local result = "{"
for i, line in ipairs(lines) do
if i ~= 1 then
result = result .. ", "
end
if long then
result = result .. "\n" .. dump_indent:rep(depth + 1)
end
result = result .. line
end
if long then
result = result .. "\n" .. dump_indent:rep(depth)
end
result = result .. "}"
markers[value] = nil
return result, long
end,
["function"] = tostring,
["thread"] = tostring,
["userdata"] = tostring
}
function dumpstr(value, depth, markers)
if not depth then
depth = 0
end
if not markers then
markers = {}
end
return dumptable[type(value)](value, depth, markers)
end
function dump(value)
print((dumpstr(value)))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.