lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I've just written a Lua function (below) that returns a textual
representation of "any" Lua object, incl. tables and nested tables. It
works quite fine. My only dissatisfaction with it, is that it quickly uses
up all of memory in case the table you feed into it contains any circular
references, which is not very surprising, since it works recursively. Are
there any easy ways to detect a situation like that before the crash is a
fact?


function asText(obj, asIndex)
   -- Returns a textual representation of "any" Lua object,
   -- incl. tables (and nested tables).
   -- Tables with circular references will cause a crash!
   -- Functions are not decompiled (of course).
   -- Try: print(asText({{"a", "b"}; c=3}))

   if type(obj) == "table" then
      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..asText(k, 1).."="..asText(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 -- asText

------------

Sincerely,

Jon Kleiser