Advertisement
Ni_Jay_Ni

functions.lua

Nov 2nd, 2023
1,131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.36 KB | Gaming | 0 0
  1. -- works like PHP's print_r(), returning the output instead of printing it to STDOUT
  2. -- daniel speakmedia com
  3. --[[ jaywha: added _G for easy Global access in ComputerCraft
  4. -- also removed leading Lua addresses like "table:4a89a0" to make it more JSON-esque --]]
  5.  
  6. function dumpvar(data)
  7.     -- cache of tables already printed, to avoid infinite recursive loops
  8.     local tablecache = {}
  9.     local buffer = ""
  10.     local padder = "    "
  11.  
  12.     local function _dumpvar(d, depth)
  13.         local t = type(d)
  14.         local str = tostring(d)
  15.         if (t == "table") then
  16.             if (tablecache[str]) then
  17.                 -- table already dumped before, so we dont
  18.                 -- dump it again, just mention it
  19.                 buffer = buffer.."\n"
  20.             else
  21.                 tablecache[str] = (tablecache[str] or 0) + 1
  22.                 buffer = buffer.."{\n"
  23.                 for k, v in pairs(d) do
  24.                     buffer = buffer..string.rep(padder, depth+1).."\""..k.."\" => "
  25.                     _dumpvar(v, depth+1)
  26.                 end
  27.                 buffer = buffer..string.rep(padder, depth).."}\n"
  28.             end
  29.         elseif (t == "number") then
  30.             buffer = buffer..str.."\n"
  31.         else
  32.             buffer = buffer.."\""..str.."\"\n"
  33.         end
  34.     end
  35.     _dumpvar(data, 0)
  36.     return buffer
  37. end
  38.  
  39. _G.dumpvar = dumpvar
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement