[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: How to prevent ..., function asText improved
- From: kleiser@... (Jon Kleiser)
- Date: Fri, 23 Apr 1999 22:23:02 +0200
I wrote you in December about a function asText(...) that I had just made,
and asked about the problem I had with handling circular references. David
Jeske replied and suggested that I should keep track of table references.
As my need to solve this just got more pressing, I made the following
improved version, along David's suggestion:
function asText(obj)
-- Returns a textual representation of "any" Lua object,
-- incl. tables (and nested tables).
-- Functions are not decompiled (of course).
-- Try: print(asText({{"a", "b"}; c=3}))
visitRef = {}
visitRef.n = 0
asTxRecur = function(obj, asIndex)
if type(obj) == "table" then
if visitRef[obj] then
return "@"..visitRef[obj]
end
visitRef.n = visitRef.n +1
visitRef[obj] = visitRef.n
local begBrac, endBrac
if asIndex then
begBrac, endBrac = "[{", "}]"
else
begBrac, endBrac = "{", "}"
end
local t = begBrac
local k, v = nil, nil
repeat
k, v = next(obj, k)
if k ~= nil then
if t > begBrac then
t = t..", "
end
t = t..asTxRecur(k, 1).."="..asTxRecur(v)
end
until k == nil
return t..endBrac
else
if asIndex then
-- we're on the left side of an "="
if type(obj) == "string" then
return obj
else
return "["..obj.."]"
end
else
-- we're on the right side of an "="
if type(obj) == "string" then
return '"'..obj..'"'
else
return tostring(obj)
end
end
end
end -- asTxRecur
return asTxRecur(obj)
end -- asText
I find this function very useful when I need to inspect complex table
structures to see if they contain what I intended them to do. When there
are several nested levels, however, the output may take some time to make
sense of.
I love Lua more and more; it's a great little language!
/Jon