Advertisement
ItsNoah

lua table print

Feb 6th, 2023 (edited)
1,104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.77 KB | None | 0 0
  1. local function totablestring(x)
  2.     return type(x) == "string" and string.format("\"%s\"", x) or tostring(x)
  3. end
  4.  
  5. local function tprint(tbl, c, indent, done)
  6.     c, indent, done = c or 0, indent or 0, done or {}
  7.     if type(tbl) == "table" then
  8.         local output, sameType = {}, true
  9.         for key, value in pairs(tbl) do
  10.             if type(key) ~= "number" then
  11.                 sameType = false
  12.             end
  13.         end
  14.         for key, value in pairs(tbl) do
  15.             table.insert(output, string.rep(" ", indent))
  16.             if type(value) == "table" and not done[value] then
  17.                 done[value] = true
  18.                 if c == 1 and sameType then
  19.                     table.insert(output, key .. " = {\n" .. string.rep(" ", indent+2) .. table.concat(value, ", ") .. "\n}\n")
  20.                 elseif c == 2 and sameType then
  21.                     table.insert(output, key .. " = { " .. table.concat(value, ", ") .. " }\n")
  22.                 else
  23.                     table.insert(output, key .. " = {\n" .. tprint(value, c, indent + 2, done) .. string.rep(" ", indent) .. "}\n")
  24.                 end
  25.             elseif type(key) == "number" then
  26.                 table.insert(output, totablestring(value))
  27.             else
  28.                 table.insert(output, key .. " = " .. totablestring(value) .. "\n")
  29.             end
  30.         end
  31.         return table.concat(output)
  32.     else
  33.         return tostring(tbl) .. "\n"
  34.     end
  35. end
  36.  
  37. local function pprint(x, compactinglvl)
  38.     compactinglvl = compactinglvl or 2
  39.  
  40.     if type(x) == "nil" then
  41.         print(tostring(nil))
  42.  
  43.     elseif type(x) == "table" then
  44.         print(tprint(x, compactinglvl))
  45.  
  46.     elseif type(x) == "string" then
  47.         print(x)
  48.  
  49.     else
  50.         print(tostring(x))
  51.     end
  52. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement