Skip to content

Instantly share code, notes, and snippets.

@Codinablack
Forked from Zbizu/dumptable.lua
Created January 19, 2022 19:01
Show Gist options
  • Save Codinablack/091d89827763a062f7c2c2f48f09c8ee to your computer and use it in GitHub Desktop.
Save Codinablack/091d89827763a062f7c2c2f48f09c8ee to your computer and use it in GitHub Desktop.
dump lua table contents to string
-- usage: dumpTable(t)
-- to dump to file:
--[[
local str = dumpTable(t)
local f = io.open("dumped_table.txt", "w+")
f:write(str)
f:close()
]]
local function getTabulation(depth)
local s = ""
for i = 1, depth do
s = s .. "\t"
end
return s
end
function dumpTable(t, depth)
if not depth then
depth = 0
end
local str = ""
if type(t) == "table" then
local n = 0
str = str .. "{\n"
for k, v in pairs(t) do
n = n + 1
str = str .. getTabulation(depth + 1) .. "[" .. (tonumber(k) and k or string.format('"%s"', k)) .. "] = " .. dumpTable(v, depth + 1) .. "\n"
end
str = str .. getTabulation(depth) .. "},\n"
if n > 0 then
return str
end
return "{},"
elseif type(t) == "string" then
return '"' .. tostring(t) .. '",'
else
return tostring(t) .. ","
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment