Skip to content

Instantly share code, notes, and snippets.

@dneumann42
Last active April 21, 2025 18:05
Show Gist options
  • Save dneumann42/27d4a87893eefdf37d26ab8e42d3df9d to your computer and use it in GitHub Desktop.
Save dneumann42/27d4a87893eefdf37d26ab8e42d3df9d to your computer and use it in GitHub Desktop.
pretty.lua
local function tostring_pretty(value, cache, ident)
if type(value) ~= "table" then
if type(value) == "string" then
return '"' .. tostring(value) .. '"'
end
return tostring(value)
end
cache = cache or {}
ident = ident or " "
if cache[value] then
return cache[value]
end
local ks = {}
for k, _ in pairs(value) do
table.insert(ks, k)
end
table.sort(ks, function(a, b)
return tostring(a) < tostring(b)
end)
local ps = { "{" }
if #ks > 0 then
table.insert(ps, "\n")
else
ident = ""
end
for i = 1, #ks do
local k = ks[i]
local v = value[k]
local vs = tostring_pretty(v, cache, ident .. " ")
if type(k) == "number" then
if i == 1 then
table.insert(ps, ident)
end
table.insert(ps, vs .. ", ")
if type(ks[i + 1]) ~= "number" then
table.insert(ps, "\n")
end
else
cache[value] = vs
table.insert(ps, ident .. k .. " = " .. vs .. ",\n")
end
end
ident = ident:sub(1, #ident - 2)
table.insert(ps, ident .. "}")
return table.concat(ps, "")
end
return tostring_pretty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment