Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print nested table using recursion in lua?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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] ] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading