具有可变数量键的 Lua 访问表

标签 lua

看一下这个示例代码:

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 访问表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32510122/

相关文章:

lua - 在 "enterFrame"中执行一次函数

python - 如何从python获取lua/translation中的类类型

lua - Lua 中的字符串化对象名称

c# - 如何将 Lua 与 .Net 集成

lua - Lua中的Wireshark解剖器

Lua string.match 提取 HTML 的一些值

c++ - 无法使用 package.loadlib 在 Lua 中动态加载库

c++ - 测试 DLL 函数的最佳方法是什么?

c++ - 在 luabind::object 中存储一个带有父类的 lua 类

sockets - 使用 LuaSocket 通过 LAN 发送 UDP 数据包