Last active
June 13, 2022 11:17
-
-
Save Zbizu/9a22253180f2786ca0c4bd18c5da19f2 to your computer and use it in GitHub Desktop.
dump lua table contents to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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