You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中通过字符串路径获取嵌套表的表项值?

通过字符串路径获取Lua表中嵌套元素的值

先看你给出的代码示例:

local a = "myTable.elem2.sub2";

myTable = {
   ["elem1"] = {
      ["sub1"] = "abc",
      ["sub2"] = "def",
      ["sub3"] = "ghi",     
   },
   ["elem2"] = {
      ["sub1"] = "jkl",
      ["sub2"] = "mno",
      ["sub3"] = "pqr",     
   },
}

要通过字符串路径a获取对应的值,核心思路是拆分路径为键数组,然后逐层遍历表结构,具体实现如下:

通用实现方案

可以写一个工具函数,直接接收路径字符串,自动完成拆分和遍历:

local function getValueByPath(path)
    -- 从全局环境开始查找
    local current = _G
    -- 按`.`拆分路径,逐个取出每个键
    for key in string.gmatch(path, "[^%.]+") do
        -- 如果当前节点不是表,说明路径无效,返回nil
        if type(current) ~= "table" then
            return nil
        end
        -- 进入下一层节点
        current = current[key]
        -- 如果节点不存在,直接返回nil
        if not current then
            return nil
        end
    end
    return current
end

-- 调用示例
local a = "myTable.elem2.sub2"
local b = getValueByPath(a)
print(b) -- 输出:mno

分步拆解逻辑

如果想自己手动实现每一步,也可以拆成两个步骤:

  1. 拆分路径字符串为键数组
local path = "myTable.elem2.sub2"
local keys = {}
-- 用正则匹配拆分,取所有非`.`的字符段
for key in string.gmatch(path, "[^%.]+") do
    table.insert(keys, key)
end
-- 此时keys = {"myTable", "elem2", "sub2"}
  1. 逐层遍历表获取值
local function getNestedValue(root, keys)
    local current = root
    for _, key in ipairs(keys) do
        if type(current) ~= "table" then
            return nil
        end
        current = current[key]
        if not current then
            break
        end
    end
    return current
end

-- 从全局环境开始查找,因为myTable是全局变量
local b = getNestedValue(_G, keys)
print(b) -- 输出:mno

注意事项

  • 如果路径中的键本身包含.,这个方法会失效,需要更换其他分隔符(比如/)并调整正则表达式
  • 函数会自动处理路径无效的情况(比如中间节点不是表、键不存在),返回nil避免报错

内容的提问来源于stack exchange,提问作者Xarxus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:02:07