Advertisement
fuxoft

anal.lua - Pretty print any (sane) table

Nov 29th, 2013
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.00 KB | None | 0 0
  1. local serfuns = {
  2.     table = function(tbl, recur)
  3.         local result = {}
  4.         local intkeys, maxint = 0, 0
  5.         for k, v in pairs(tbl) do
  6.             if intkeys and type(k) == "number" then
  7.                 if (k > 0) and (k % 1 == 0) then
  8.                     intkeys = intkeys + 1
  9.                     if k > maxint then
  10.                         maxint = k
  11.                     end
  12.                 end
  13.             else
  14.                 intkeys = false
  15.             end
  16.             table.insert(result, "["..anal(k, recur).."]="..anal(v, recur))
  17.         end
  18.         if maxint == intkeys then
  19.             result = {}
  20.             for i,v in ipairs(tbl) do
  21.                 table.insert(result, anal(v))
  22.             end
  23.         end
  24.         return ("{"..table.concat(result,", ").."}")
  25.     end,
  26.     string = function(x) return string.format("%q", x) end,
  27.     ["function"] = tostring,
  28.     boolean = tostring,
  29.     userdata = tostring
  30. }
  31.  
  32. _G.anal = function (thing, recur)
  33.     recur = recur or {}
  34.     local serfun = serfuns[type(thing)]
  35.     if not serfun then
  36.         return thing
  37.     end
  38.     if recur[thing] then
  39.         return "*** REKURZE ***"
  40.     end
  41.     if type(thing) == "table" then
  42.         recur[thing] = true
  43.     end
  44.     return serfun(thing, recur)
  45. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement