Search code examples
lua-tablelua-5.3

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


I have a configurable value of a table fetch function which i get as an input string. I need that string to be executed as a code and fetch a value from the nested table.

I tried using load(string), its not working

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

print(load(string)) should print value1.


Solution

  • Below code works

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