-
-
Save zhang1career/005a6b5bdca5a4d023637cde1d2a77c4 to your computer and use it in GitHub Desktop.
This is a handy recursive data printer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> rPrint({first={true,1.3,"abc",{1,2,5}},22,33,last={nil,5},2},nil,"Junk", ngx.say) | |
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ 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, pFunc) -- recursive Print (structure, limit, indent, printFunction) | |
l = (l) or 100; i = i or ""; -- default item limit, indent string | |
pFunc = pFunc or print -- default print function | |
if (l<1) then pFunc "ERROR: Item limit reached."; return l-1 end; | |
local ts = type(s); | |
if (ts ~= "table") then pFunc (i.."\t"..ts.."\t".., s); return l-1 end | |
pFunc (i.."\t"..ts); -- print "table" | |
for k,v in pairs(s) do -- print "[KEY] VALUE" | |
l = rPrint(v, l, i.."\t["..tostring(k).."]", pFunc); | |
if (l < 0) then break end | |
end | |
return l | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An user-defined print method has been added into rPrint.