Lua:将嵌套表的索引作为函数参数传递?

Lua:将嵌套表的索引作为函数参数传递?,lua,lua-table,Lua,Lua Table,有没有可能有一个函数可以访问表中任意嵌套的条目? 以下示例仅适用于一个表。但在我的实际应用程序中,我需要该函数为给定的嵌套索引检查几个不同的表 local table1 = { value1 = "test1", subtable1 = { subvalue1 = "subvalue1", }, } local function myAccess(index) return table1[index] end -- This i

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

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???"))

除非使用load将其视为Lua代码或创建一个函数在表上漫游,否则无法使用字符串来完成此操作

您可以创建一个函数,将字符串拆分为。拿到每把钥匙,然后一把一把地走


您可以使用gmatch+1 local-over-gmatch和当前表来执行此操作。

除非使用load将其视为Lua代码,或者使用函数在表上漫游,否则无法使用字符串执行此操作

您可以创建一个函数,将字符串拆分为。拿到每把钥匙,然后一把一把地走


您可以使用gmatch+一个本地gmatch和当前表来完成此操作。

@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"))

@斯巴尔:这就是你的建议吗?不管怎样,它还是有效的,所以谢谢

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"))

如果有其他方法,参数不需要是字符串?一个接一个是如何工作的?@Linus好的,如果你能在脚本中完成它,只要做table1.subtable1.subvalue1,如果它永远不变。gmatch会一个接一个地完成,因为它会为每个密钥调用。对于string.gmatchindex中的键,[^.]+do printkey endMy函数应检查table1.subtable1.subvalue1是否存在,如果不存在,则应返回table2.subtable1.subvalue1。所以我必须告诉我的函数它应该检查subtable1.subvalue1.makelocalbeforgmatch到table1,使用gmatch键并转到下一个table。检查是否为零。我发布了另一个答案。这就是你的建议吗?如果有其他方法,参数不需要是字符串?一个接一个是如何工作的?@Linus好的,如果你能在脚本中完成它,只要做table1.subtable1.subvalue1,如果它永远不变。gmatch会一个接一个地完成,因为它会为每个密钥调用。对于string.gmatchindex中的键,[^.]+do printkey endMy函数应检查table1.subtable1.subvalue1是否存在,如果不存在,则应返回table2.subtable1.subvalue1。所以我必须告诉我的函数它应该检查subtable1.subvalue1.makelocalbeforgmatch到table1,使用gmatch键并转到下一个table。检查是否为零。我发布了另一个答案。这是你的建议吗?