Skip to content

Instantly share code, notes, and snippets.

@stuby
Created April 23, 2013 17:54
Show Gist options
  • Save stuby/5445834 to your computer and use it in GitHub Desktop.
Save stuby/5445834 to your computer and use it in GitHub Desktop.
This is a handy recursive data printer.
> rPrint({first={true,1.3,"abc",{1,2,5}},22,33,last={nil,5},2},nil,"Junk")
Junk table
Junk [1] number 22
Junk [2] number 33
Junk [3] number 2
Junk [last] table
Junk [last] [2] number 5
Junk [first] table
Junk [first] [1] boolean true
Junk [first] [2] number 1.3
Junk [first] [3] string abc
Junk [first] [4] table
Junk [first] [4] [1] number 1
Junk [first] [4] [2] number 2
Junk [first] [4] [3] number 5
--[[ rPrint(struct, [limit], [indent]) Recursively print arbitrary data.
Set limit (default 100) to stanch infinite loops.
Indents tables as [KEY] VALUE, nested tables as [KEY] [KEY]...[KEY] VALUE
Set indent ("") to prefix each line: Mytable [KEY] [KEY]...[KEY] VALUE
--]]
function rPrint(s, l, i) -- recursive Print (structure, limit, indent)
l = (l) or 100; i = i or ""; -- default item limit, indent string
if (l<1) then print "ERROR: Item limit reached."; return l-1 end;
local ts = type(s);
if (ts ~= "table") then print (i,ts,s); return l-1 end
print (i,ts); -- print "table"
for k,v in pairs(s) do -- print "[KEY] VALUE"
l = rPrint(v, l, i.."\t["..tostring(k).."]");
if (l < 0) then break end
end
return l
end
@boristyukin
Copy link

awesome - exactly what i needed!

@cauu
Copy link

cauu commented Feb 28, 2015

great! helps a lot!

@ZenToad
Copy link

ZenToad commented Jul 28, 2017

Very nice. Thank you

@gingerbeardman
Copy link

Thanks!

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