Skip to content

Instantly share code, notes, and snippets.

@zhangzhhz
Last active February 11, 2023 16:39
Show Gist options
  • Save zhangzhhz/52b64203142ede9d8249c36bd302333d to your computer and use it in GitHub Desktop.
Save zhangzhhz/52b64203142ede9d8249c36bd302333d to your computer and use it in GitHub Desktop.
Dump a Lua table
#!/usr/bin/env lua
t = { a = 1, b = 2, h = "hello", x = { m = 1, n = "hello world" }, 3,
y = { "y", z = "hello there", aa = { a1 = 1, a2 = 2, x = "xyz" } },
bool = { b1 = true, b2 = false, [true] = true, [false] = false },
[100] = "one hundred", ["hello world"] = 100, f = function() return "Returned from a function" end }
function dump(t, indentLevel)
local indentLevel = indentLevel or 1
local str = "{\n"
for k, v in pairs(t) do
local embeded_v = ""
if type(v) == "table" then
if v == t then
v = "<reference to original table>"
else
embeded_v = dump(v, indentLevel + 1)
end
elseif type(v) == "string" then
v = string.format("%q", v)
elseif type(v) == "boolean" or type(v) == "function" then
v = string.format("%s", v)
end
if type(v) == "table" then
v = embeded_v
end
if type(k) == "number" or type(k) == "boolean" then
k = string.format("[%s]", k)
elseif type(k) == "string" and string.find(k, "%s") then
k = string.format("[%q]", k)
end
str = str .. string.rep(" ", indentLevel * 4) .. k .. " = " .. v .. ",\n"
end
str = str .. string.rep(" ", (indentLevel - 1) * 4) .. "}"
return str
end
print(dump(t))
--[[
{
[1] = 3,
["hello world"] = 100,
f = function: 0xaaaae1456e70,
a = 1,
b = 2,
bool = {
[false] = false,
[true] = true,
b1 = true,
b2 = false,
},
[100] = "one hundred",
h = "hello",
y = {
[1] = "y",
aa = {
x = "xyz",
a2 = 2,
a1 = 1,
},
z = "hello there",
},
x = {
m = 1,
n = "hello world",
},
}
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment