Advertisement
Guest User

pretty-print variable dump lua debugging print_r() dir()

a guest
Aug 21st, 2012
2,346
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.04 KB | None | 1 0
  1. -- works like PHP's print_r(), returning the output instead of printing it to STDOUT
  2. -- daniel speakmedia com
  3.  
  4. function dumpvar(data)
  5.     -- cache of tables already printed, to avoid infinite recursive loops
  6.     local tablecache = {}
  7.     local buffer = ""
  8.     local padder = "    "
  9.  
  10.     local function _dumpvar(d, depth)
  11.         local t = type(d)
  12.         local str = tostring(d)
  13.         if (t == "table") then
  14.             if (tablecache[str]) then
  15.                 -- table already dumped before, so we dont
  16.                 -- dump it again, just mention it
  17.                 buffer = buffer.."<"..str..">\n"
  18.             else
  19.                 tablecache[str] = (tablecache[str] or 0) + 1
  20.                 buffer = buffer.."("..str..") {\n"
  21.                 for k, v in pairs(d) do
  22.                     buffer = buffer..string.rep(padder, depth+1).."["..k.."] => "
  23.                     _dumpvar(v, depth+1)
  24.                 end
  25.                 buffer = buffer..string.rep(padder, depth).."}\n"
  26.             end
  27.         elseif (t == "number") then
  28.             buffer = buffer.."("..t..") "..str.."\n"
  29.         else
  30.             buffer = buffer.."("..t..") \""..str.."\"\n"
  31.         end
  32.     end
  33.     _dumpvar(data, 0)
  34.     return buffer
  35. end
  36.  
  37.  
  38. --[[
  39. print(dumpvar({
  40.     [1] = "this is the first element",
  41.     [2] = "and this is the second",
  42.     [3] = 3,
  43.     [4] = 3.1415,
  44.     ["nested"] = {
  45.         ["lua"] = "is cool but",
  46.         ["luajit"] = "is fucking awesome!"
  47.     },
  48.     ["some-files"] = {
  49.         [0] = io.stdin,
  50.         [1] = io.stdout,
  51.         [2] = io.stderr
  52.     }
  53. }))
  54.  
  55. -- outputs:
  56.  
  57. (table: 0x41365f60) {
  58.     [1] => (string) "this is the first element"
  59.     [2] => (string) "and this is the second"
  60.     [3] => (number) 3
  61.     [4] => (number) 3.1415
  62.     [nested] => (table: 0x41365fb0) {
  63.         [lua] => (string) "is cool but"
  64.         [luajit] => (string) "is fucking awesome!"
  65.     }
  66.     [some-files] => (table: 0x41366048) {
  67.         [0] => (userdata) "file (0x3f1e79b6a0)"
  68.         [1] => (userdata) "file (0x3f1e79b780)"
  69.         [2] => (userdata) "file (0x3f1e79b860)"
  70.     }
  71. }
  72.  
  73. ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement