【问题标题】:Lua: Passing index of nested tables as function arguments?Lua:将嵌套表的索引作为函数参数传递?
【发布时间】:2021-03-30 19:16:54
【问题描述】:

是否有可能拥有一个可以访问任意嵌套表条目的函数? 以下示例仅适用于一张表。但是在我的实际应用程序中,我需要该函数来检查给定(嵌套)索引的几个不同表。

local table1 = {
  value1 = "test1",
  subtable1 = {
    subvalue1 = "subvalue1",
  },
}

local function myAccess(index)
  return table1[index]
end

-- This is fine:
print (myAccess("value1"))

-- But how do I access subtable1.subvalue1?
print (myAccess("subtable1.subvalue1???"))

【问题讨论】:

    标签: lua lua-table


    【解决方案1】:

    除非您使用 load 将其视为 Lua 代码或创建一个在桌子上行走的函数,否则您将无法使用字符串执行此操作。

    您可以创建一个函数,将您的字符串按. 拆分以获取每个键,然后一个接一个地进行。

    您可以使用 gmatch + 一个本地高于当前表的 gmatch 来做到这一点。

    【讨论】:

    • 参数不需要是字符串,如果有其他方法呢? “一个接一个”是如何工作的?
    • @Linus 很好,如果你可以在脚本中做到这一点,只要做到table1.subtable1.subvalue1,如果它永远不会改变。由 gmatch 逐一完成,因为它将为每个键调用。 for key in string.gmatch(index, "[^.]+") do print(key) end
    • 我的函数应该检查 table1.subtable1.subvalue1 是否存在,如果不存在,它应该返回 table2.subtable1.subvalue1。所以我必须告诉我的函数它应该检查 subtable1.subvalue1。
    • 在 gmatch 到 table1 之前创建一个本地,使用 gmatch 键并转到下一个表。检查它是否为零。
    • 我发布了另一个答案。这是你的建议吗?
    【解决方案2】:

    @Spar:这就是你的建议吗?它仍然有效,所以谢谢!

    local table1 = {
      value1 = "test1",
      subtable1 = {
        subvalue1 = "subvalue1",
      },
    }
    
    
    local function myAccess(index)
      
      local returnValue = table1
      for key in string.gmatch(index, "[^.]+") do 
        if returnValue[key] then
          returnValue = returnValue[key]
        else
          return nil
        end
      end
      
      return returnValue
    end
    
    -- This is fine:
    print (myAccess("value1"))
    
    -- So is this:
    print (myAccess("subtable1.subvalue1"))
    

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多