How to call Lua table value explicitly when using integer counter (i,j,k) in a for loop to make the table name/address?

Viewed 69

I have to be honest that I don't quite understand Lua that well yet. I am trying to overwrite a local numeric value assigned to a set table address (is this the right term?).

The addresses are of the type:

project.models.stor1.inputs.T_in.default, project.models.stor2.inputs.T_in.default and so on with the stor number increasing.

I would like to do this in a for loop but cannot find the right expression to make the entire string be accepted by Lua as a table address (again, I hope this is the right term).

So far, I tried the following to concatenate the strings but without success in calling and then overwriting the value:

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

EDIT:

I think I found the solution as per 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
1 Answers

You were almost close.

Lua supports this representation by providing a.name as syntactic sugar for a["name"].

Read more: https://www.lua.org/pil/2.5.html

You can use only one syntax in time.

Either tbl.key or tbl["key"].

The limitation of . is that you can only use constant strings in it (which are also valid variable names).

In square brackets [] you can evaluate runtime expressions.

Correct way to do it:

project.models["stor"..k].inputs.T_in.default = 25

The . in models.["stor"..k] is unnecessary and causes an error. The correct syntax is just models["stor"..k].

Related