动态访问table.subtable值

时间:2015-08-30 12:21:31

标签: dynamic lua lua-table

我试图以动态方式访问子表值,但我找不到合适/聪明的方法来执行此操作。以下是我想要实现的示例代码:

local var = "mySubTable1" --this value is different every time

local myTable = {
    mySubTable1 = {"hello","world","goodbye","city"},
    mySubTable2 = {"this", "is", "a", "test"},
    ...
}

print(myTable.var[3]) --I know this doesnt work, but how can I fix this?

1 个答案:

答案 0 :(得分:1)

表格由以下关键字索引:

myTable[expression_that_evaluates_to_the_key]

如果键是一个字符串并且碰巧是一个有效的Lua标识符,那么可以使用这个语法糖:

myTable.mySubTable1

你已经知道那条捷径。回到基础:

print(myTable[var][3])