I want to print this table using recursion and not by using for loop. I am trying to avoid repeating code.
local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
for k1, v1 in pairs(v) do
local rowtext = ""
rowtext = string.format("[%s %s] ",k, v1)
request_headers_all = request_headers_all .. rowtext
end
else
local rowtext = ""
rowtext = string.format("[%s %s] ", k, v)
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end
print(DeepPrint (t))
Expected output (order doesn’t matter):
[y 5] [x 0] [other 10] [other 10] [other 10] [other 11]
>Solution :
You can simply remove the inner loop and make a call to DeepPrint again using the value of v – the table:
local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
request_headers_all = request_headers_all .. "[" .. k .. " " .. DeepPrint(v) .. "] "
else
local rowtext = ""
rowtext = string.format("[%s %s] ", k, v)
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end
print(DeepPrint (t))
Produces:
[y 5] [x 0] [other [1 10] [2 10] [3 10] [4 11] ]
Note that you are not going to get these in order. Hashes are unordered, so you cannot guarantee that x will precede y will precede other.
Update: Strip out array indices for pure arrays:
local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
request_headers_all = request_headers_all .. "[" .. k .. " " .. DeepPrint(v) .. "] "
else
local rowtext = ""
if type(k) == "string" then
rowtext = string.format("[%s %s] ", k, v)
else
rowtext = string.format("[%s] ", v)
end
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end
Output:
[y 5] [x 0] [other [10] [10] [10] [11] ]