Why increasing table lenght don't affects on "for" loop?

I’m trying recreate 3-in-row game - bejeweled. Now, I’m making Flame gem. And I have 1 problem with for loop. When Flame gem matched, for loop starts, and then, every gem near it adds to table LenghtX, which is used to determine how much for loop should run code.
The main problem of for loop - that if I increase lenght of LenghtX, loop won’t detect it at all!

Example:

Array consist of 3 variables - 1, 2, 3.
I start for loop:

for i = 1, #Array , 1 do
    code here will be shown below.
end

Now, I’ll insert into Array 3 variables: (but I want 17)

for i = 1, #Array , 1 do
	table.insert(Array , 3 + i)
	print("Inserted")
	if #Array > 20 then -- just to control lopp if all will be TOO good
		break
	end
end

And in the output, we will see “Inserted” only 3 times, but I expect 17.


If I will add variable, which will be also increased by 1, result won’t change:

Can someone help me, and say, how I can handle this weird problem with for loop?

Lua 5.1 Reference Manual states that:

  • All three control expressions are evaluated only once, before the loop starts. They must all result in numbers.

So in your case #Array is evaluated once which is 3 then the second expression will stay that way even if the length of the Array changes.

The for loop will not evalulate the #Array again after its first evaluation.

I suggest you use the while loop in this case.

local i = 1
while i < #Array do
        ...
        i += 1
end
3 Likes