看一下这个示例代码:

tbl = {
    status = {
        count = 0
    }
}

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

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


我希望能够通过可变数量的字符串键来动态访问表条目,有没有办法做到这一点?

最佳答案

这就是递归的目的:

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

关于lua - Lua访问表,具有可变数量的 key ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32510122/

10-13 05:35