
Share Your Code
Browse Code
- All (906)
-
(94)
-
(85)
-
(44)
-
(4)
-
(42)
-
(136)
-
(21)
-
(41)
-
(13)
-
(65)
-
(151)
-
(210)
print_r() implementation (dumps everything as human readable text)
This is "dumper" function in the style of "print_r()" from php.
A helper which I for the most part gathered from the lua wiki and fine tuned it to do exactly what I expect from it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | function print_r ( t ) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then print(indent.."*"..tostring(t)) else print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then print(indent.."["..pos.."] => "..tostring(t).." {") sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) print(indent..string.rep(" ",string.len(pos)+6).."}") elseif (type(val)=="string") then print(indent.."["..pos..'] => "'..val..'"') else print(indent.."["..pos.."] => "..tostring(val)) end end else print(indent..tostring(t)) end end end if (type(t)=="table") then print(tostring(t).." {") sub_print_r(t," ") print("}") else sub_print_r(t," ") end print() end |
I use it inside a mini module which contains a lot of different helper functions I use for my projects.
Replies
Hey, thanks for this! I've wanted to dump tables to the console countless times, but I never took the time to write the code to do it.
One small issue, though. When printing keys, strings should be quoted when placed in square brackets.
With the current code:
print_r {"Bob", "James", ["2"] = "Sally"}
-- output
--table: 0x4c5680 {
-- [1] => "Bob"
-- [2] => "James" <-- James and Sally cannot both have
-- [2] => "Sally" <-- the same key in the same table
--}
I added pos = type(pos) == "string" and '"' .. pos .. '"' or pos as the first line inside the for loop to deal with this.
print_r {"Bob", "James", ["2"] = "Sally"}
-- output
--table: 0x18d0e50 {
-- [1] => "Bob"
-- [2] => "James"
-- ["2"] => "Sally"
--}
Thanks again for the code!
Legend! Just what I was looking for.
I'm using this:
1 2 3 4 5 6 7 8 9 10 11 12 | function inspect(obj) if obj==nil then return "nil" end if obj==true then return "true" end if obj==false then return "false" end if type(obj)=="string" then return obj end local json = require "json" return json.encode({obj}) end function debug(obj) print(inspect(obj)) end |
Easy and clear ;)


I'm a bit late to the party here, but thanks, that's a real handy tool.