for-loop - 在for循环中使用整数计数器(i,j,k)来创建表名称/地址时,如何显式调用Lua表值?

标签 for-loop lua lua-table

说实话,我还不太了解 Lua。我正在尝试覆盖分配给设置表地址的本地数值(这是正确的术语吗?)。

地址的类型为:

project.models.stor1.inputs.T_in.defaultproject.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.keytbl["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/

相关文章:

networking - 用于对声音进行分类的时间 CNN : cur_target assertion

performance - 在我的速度测试中,Lua 表哈希索引比数组索引更快。为什么?

lua - 如何在初始化期间自引用表

c - C 中接收相同 ID 的线程

python - for循环在python中在哪里结束

python - 对空列表进行 for 循环实际上会花费时间/资源吗?

c - Lua c lib Windows : The specified procedure could not be found

c++ - 从 lua_pcall(L, 0, 0, 0) 获取所有错误

c++ - LuaPlus 从 C++ 操作表

r - 如何为这些回归建立一个循环?