Created
February 9, 2011 03:28
-
-
Save JakobOvrum/817830 to your computer and use it in GitHub Desktop.
table.print function with custom sink support and circular reference detection.
This file contains hidden or 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
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