说实话,我还不太了解 Lua。我正在尝试覆盖分配给设置表地址的本地数值(这是正确的术语吗?)。
地址的类型为:
project.models.stor1.inputs.T_in.default
、project.models.stor2.inputs.T_in.default
等与 stor
数量不断增加。
我想在 for 循环中执行此操作,但找不到正确的表达式来使 Lua 接受整个字符串作为表地址(再次,我希望这是正确的术语)。
到目前为止,我尝试了以下方法来连接字符串,但没有成功调用并覆盖该值:
for k = 1,10,1 do
project.models.["stor"..k].inputs.T_in.default = 25
end
for k = 1,10,1 do
"project.models.stor"..j..".T_in.default" = 25
end
编辑:
我想我按照 https://www.lua.org/pil/2.5.html 找到了解决方案:
A common mistake for beginners is to confuse a.x with a[x]. The first form represents a["x"], that is, a table indexed by the string "x". The second form is a table indexed by the value of the variable x. See the difference:
for k = 1,10,1 do
project["models"]["stor"..k]["inputs"]["T_in"]["default"] = 25
end
最佳答案
你已经很接近了。
Lua supports this representation by providing a.name as syntactic sugar for a["name"].
Read more: https://www.lua.org/pil/2.5.html
您一次只能使用一种语法。
要么tbl.key
或tbl["key"]
.
.
的限制是你只能在其中使用常量字符串(也是 valid variable names )。
方括号内 []
您可以计算运行时表达式。
正确的做法:
project.models["stor"..k].inputs.T_in.default = 25
.
在models.["stor"..k]
是不必要的并且会导致错误。正确的语法只是 models["stor"..k]
.
关于for-loop - 在for循环中使用整数计数器(i,j,k)来创建表名称/地址时,如何显式调用Lua表值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64901475/