Skip to content

Instantly share code, notes, and snippets.

@Phroneris
Last active July 11, 2026 20:35
Show Gist options
  • Select an option

  • Save Phroneris/56c1edaf3186b09d289184b8188098a4 to your computer and use it in GitHub Desktop.

Select an option

Save Phroneris/56c1edaf3186b09d289184b8188098a4 to your computer and use it in GitHub Desktop.
[Lua] Print table contents recursively and more usefully
-- Original: [Lua] Print table contents recursively https://gist.github.com/hashmal/874792
-- Additional Features:
-- * Safe for any types by tostring(): https://gist.github.com/xytis/5361405
-- * Explicitly indicate empty tables
-- * Avoid extracting already-printed tables to prevent infinite loop for self-referential tables such as _G
-- * Format strings like literals to improve readability and preserve indentation
function tprint(tbl, indent, tprinted)
indent = indent or 0
tprinted = tprinted or { [tostring(tbl)] = true }
local indentstr = string.rep(" ", indent)
if not next(tbl) then
print(indentstr .. "(empty)")
else
for k, v in pairs(tbl) do
local vstr = tostring(v)
local header = string.format("%s[%s] ", indentstr, k)
if type(v) == "table" then
if tprinted[vstr] then
print(header .. vstr .. " (already printed)")
else
tprinted[vstr] = true
print(header .. vstr)
tprinted = tprint(v, indent + 1, tprinted)
end
else
if type(v) == "string" then
v = v:gsub("\\", "\\\\"):gsub('"', '\\"')
:gsub("\n", "\\n"):gsub("\r", "\\r")
:gsub("\t", "\\t"):gsub("\v", "\\v")
:gsub("\a", "\\a"):gsub("\b", "\\b"):gsub("\f", "\\f")
vstr = '"' .. v .. '"'
end
print(header .. vstr)
end
end
end
return tprinted
end
local tbl = { 42, true, a = "A", c = "C:\\Windows" }
tbl.lines = [[Lorem
ipsum
dolor]]
tbl.empty = {}
tbl.nested = { 100, 200, { 300 } }
tbl.square = function(v) return v * v end
tbl.self = tbl
tprint(tbl)
--[[
[1] 42
[2] true
[self] table: 0x23779f00 (already printed)
[square] function: 0x2376a2d0
[empty] table: 0x2376a338
(empty)
[nested] table: 0x23766678
[1] 100
[2] 200
[3] table: 0x2376a298
[1] 300
[lines] "Lorem\nipsum\ndolor"
[c] "C:\\Windows"
[a] "A"
]]--
@Phroneris

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment