Lua: how to improve print table at specific table depth

Viewed 29

This is my custom function:

function scope(tbl, depth)
    if (depth > 0) then
        for k, v in pairs(tbl) do
            if (type(v) ~= "table") then
                print(v)
            else
                scope(v, depth - 1)
            end
        end
    end
end

This is the usage: let

stuff = {
    fruit = {
        yellow = {
            "Banana"
        }, -- depth = 3
        red = {
            "Apple"
        } -- depth = 3
    },
    city = {
        "Toronto"
    }, -- depth = 2
    name = {
        "Claudia"
    } -- depth = 2
}

scope(stuff, 2) returns

Toronto
Claudia

Otherwise, scope(stuff, 3) returns

Banana
Apple
Toronto
Claudia

Advice on how to improve it? Maybe insert some code that displays nil if, as here, I specify depth value of 1 or a number greater than 3 (the depth of the table).

0 Answers
Related