动态访问 table.subtable 值
access table.subtable value dynamically
我正在尝试以动态方式访问子表值,但找不到 proper/smart 方法来执行此操作。这是我想要实现的示例代码:
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?
A table 由这样的键索引:
myTable[expression_that_evaluates_to_the_key]
如果键是一个字符串并且恰好是一个有效的 Lua 标识符,那么可以使用这个语法糖:
myTable.mySubTable1
您已经知道该快捷方式。回到基本面:
print(myTable[var][3])
我正在尝试以动态方式访问子表值,但找不到 proper/smart 方法来执行此操作。这是我想要实现的示例代码:
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?
A table 由这样的键索引:
myTable[expression_that_evaluates_to_the_key]
如果键是一个字符串并且恰好是一个有效的 Lua 标识符,那么可以使用这个语法糖:
myTable.mySubTable1
您已经知道该快捷方式。回到基本面:
print(myTable[var][3])