使用可变数量的键访问 Lua 表

看一下这个示例代码:

tbl = {
    status = {
        count = 0
    }
}

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

increase(tbl, "status", "count") -- 将 tbl["status"]["count"] 增加 1

我想通过可变数量的字符串键动态访问表项,有没有办法实现这一点?

点赞
用户1826176
用户1826176
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") -- 将 tbl["status"]["count"] 增加 1
2015-09-10 19:47:36
用户3125367
用户3125367

这就是递归的用处:

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)

输出结果:

chapter A
  page 10: 1
  page 13: 2
chapter B
  page 42
    line 3: 1
2015-09-11 01:52:44