[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Function to improve on 'print(table)'...
- From: Duck <duck@...>
- Date: Sun, 19 Aug 2007 16:25:19 +1000 (EST)
In another thread, someone asked for a feature so that instead of:
> print(table)
table: 0x806e468
you might be able to do something like this:
> dumptable(table)
{ [1]
setn()
insert()
getn()
foreachi()
maxn()
foreach()
concat()
sort()
remove()
}
or like this:
> t = {}
> t[1] = "banana"
> t[2] = { fruit = "mango", qty = 45 }
> dumptable(t)
{ [1]
1 "banana"
2 { [2]
qty = 45
fruit "mango"
}
}
> t[3] = t
> dumptable(t)
{ [1]
1 "banana"
2 { [2]
qty = 45
fruit "mango"
}
3 {}-->[1]
}
for which I use something like this (the numbers in [square brackets]
aren't table indexes, but just cross references to tables which have
already been seen -- try dumptable(_G) to see what I mean). It's meant to
be a sort of legible serialisation for troubleshooting your data.
---cut here---
function dumptable(tab)
local tableseen = {}
local tableseqno = 1
local tablestrmax = 45
local tableindent = 3
local function tabledump(tab,n)
if tab == nil then io.write("nil\n"); return end
if tableseen[tab] ~= nil then return end
tableseen[tab] = tableseqno
io.write("{ ["..tableseqno.."]\n")
tableseqno = tableseqno + 1
for k, v in pairs(tab) do
local id = tostring(k)
local val = tostring(v)
io.write(string.format("%s%s",string.rep(" ",n),id))
if type(v) == "function" then
io.write("()\n")
elseif type(v) == "string" then
io.write(' "'..val:sub(1,tablestrmax))
if (val:len() > tablestrmax) then io.write("...") end
io.write('"\n')
elseif type(v) == "table" then
io.write(" ")
if tableseen[v] ~= nil then
io.write("{}-->["..tableseen[v].."]\n")
else
tabledump(v,n+tableindent)
end
elseif type(v) == "number" then
io.write(" = "..val.."\n")
else
io.write(" "..val.."\n")
end
end
io.write(string.rep(" ",n-tableindent).."}\n")
end
tabledump(tab,tableindent)
end
---cut here---