user1826176
user1826176

Reputation: 309

Lua access table with variable amount of keys

Take a look at this example code:

tbl = {
    status = {
        count = 0
    }
}

function increase(t, ...)
    -- ???
end

increase(tbl, "status", "count") -- increases tbl["status"]["count"] by 1

I want to be able to dynamically access the table entries via a variable amount of string keys, is there any way to do this?

Upvotes: 2

Views: 360

Answers (2)

user3125367
user3125367

Reputation: 3000

That's what recursion is for:

function increase(t, k1, k2, ...)
    if k2 == nil then
        t[k1] = (t[k1] or 0) + 1
    else
        if t[k1] == nil then
            t[k1] = { } -- remove this to disable auto-creation
        end
        increase(t[k1], k2, ...)
    end
end

local t = { }
increase(t, "chapter A", "page 10")
increase(t, "chapter A", "page 13")
increase(t, "chapter A", "page 13")
increase(t, "chapter B", "page 42", "line 3");

function tprint(t, pre)
    pre = pre or ""
    for k,v in pairs(t) do
        if type(v) == "table" then
            print(pre..tostring(k))
            tprint(v, pre.."  ")
        else
            print(pre..tostring(k)..": "..tostring(v))
        end
    end
end

tprint(t)

output:

chapter A
  page 10: 1
  page 13: 2
chapter B
  page 42
    line 3: 1

Upvotes: 4

user1826176
user1826176

Reputation: 309

tbl = {
    status = {
        count = 0
    }
}

function increase(t, ...)

    local target = t 
    local args = {...}  
    local last = "" 

    for i, key in pairs(args) do
        if i == #args then
            last = key
        else
            target  = target[key]
        end
    end

    target[last] = target [last] + 1
end

increase(tbl, "status", "count") -- increases tbl["status"]["count"] by 1

Upvotes: 1

Related Questions