• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

Print table at specific table depth (1 Viewer)

Unitscan

Newcomer
Joined
Mar 25, 2022
Messages
1
Reaction score
0
I have this table

Lua:
stuff = {
    fruit = {
        yellow = {
            "Banana"
            },
        red = {
            "Apple"
            }
        },
    city = {
        "Toronto"
        },
    name = {
        "Claudia"
        }
}

function scope(tbl,depth)
    for k, v in pairs(tbl) do
        -- my code here
    end
end

I would like to make it so that by calling the function scope(stuff, 2) the output be

Code:
Toronto
Claudia

Otherwise, by calling the function scope(stuff, 3) the output be

Code:
Banana
Apple

I know you have to use the recursive functions, but how?

Thanks in advance
 

GavinW

Newcomer
Creator of RiscLua
Joined
Oct 21, 2020
Messages
54
Reaction score
20
Age
83
Location
UK
Website
www.wra1th.plus.com
Lua:
local scope
scope = function (t, level)
  if level == 1 then
     for _, v in pairs (t) do
        if type (v) == "string" then print (v) end -- if
      end -- for
      return
  else
     for _, v in pairs (t) do
        if type (v) == "table" then scope (v, level - 1) end -- if
     end -- for
  end -- if
 end -- function
 
Top