1

Is it possible to have a function that can access arbitrarily nested entries of a table? The following example is just for one table. But in my real application I need the function to check several different tables for the given (nested) index.

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

2 Answers 2

2

You won't be able to do this using a string unless you use load to treat it as Lua code or make a function to walk on a table.

You can make a function which will split your string by . to get each key and then go one by one.

You can do this using gmatch + one local above gmatch with current table.

Sign up to request clarification or add additional context in comments.

6 Comments

The argument does not need to be a string, if there is another way? How does "going one by one" work?
@Linus well if you can do it in script just do table1.subtable1.subvalue1, if it never changes. one by one is done by gmatch because it will be called for each key. for key in string.gmatch(index, "[^.]+") do print(key) end
My function should check if table1.subtable1.subvalue1 exists, and if not it should return table2.subtable1.subvalue1. So I have to tell my function it should check for subtable1.subvalue1.
make a local before gmatch to table1, use gmatch keys and go to next table. check if it's nil.
I posted another answer. Is this what you were suggesting?
|
1

@Spar: Is this what you were suggesting? It works anyway, so thanks!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.