如何将字符串转换为 lua 代码以从嵌套的 table 中读取值

How to Convert a string to lua code to read value from nested table

我有一个 table 获取函数的可配置值,我将其作为输入字符串获取。我需要将该字符串作为代码执行并从嵌套的 table.

中获取一个值

我尝试使用 load(string),它不起作用

local function main()
  local t = {
    ["name1"] = "value1",
    ["name2"] = {["name1"] = "value1",
      ["name2"] = { 1, false, true, 23.54, "a 1 string" },
      name3 = nil
    },
    name3 = nil
  }
  local string = 't.name2.name1'
  print(type(string))
  print(load(string))
end

print(load(string)) 应该打印 value1.

下面的代码有效

local function main()

  t = {
    ["name1"] = "value1",
    ["name2"] = {["name1"] = "value1",
      ["name2"] = { 1, false, true, 23.54, "a 1 string" },
      name3 = nil
    },
    name3 = nil
  }
  string = "t.name2.name1"
  print(type(string))
  val = load("return "..string)()
  print(val)
end