Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Created February 9, 2011 03:28
Show Gist options
  • Save JakobOvrum/817830 to your computer and use it in GitHub Desktop.
Save JakobOvrum/817830 to your computer and use it in GitHub Desktop.
table.print function with custom sink support and circular reference detection.
local pairs = pairs
local type = type
local tostring = tostring
local print = print
local table = table
local next = next
module "tableprint"
local function tableprint(t, tab, sink, cache)
for k, v in pairs(t) do
if type(v) ~= "table" then
sink(("%s%s: %s (%s)"):format(tab, tostring(k), tostring(v), type(v)))
else
local id = cache[v] or cache.id + 1
sink(("%s%s: (table) #%d"):format(tab, tostring(k), id))
if not next(v) then
sink(tab .. "\t(empty)")
else
if cache[v] then
sink(tab .. "\t...")
else
cache[v] = id
cache.id = id
tableprint(v, tab .. "\t", sink, cache)
end
end
end
end
end
defaultSink = print
function table.print(t, sink)
sink = sink or defaultSink
tableprint(t, "", sink, {[t] = 0, id = 0})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment