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

问题描述

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

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 + 一个本地高于当前表的 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"))