Search code examples
luaiteratorlua-5.1

Lua: Is decreasing iterator from inside of loop possible?


array={}
size=10

math.randomseed(os.time())
for i=1,size do
    array[i]=math.random(size)
    if(i>1) then
        for j=1,i do
            if  array[j]==array[i] then
                i=i-1
                break
            end
        end
    end
end

for i=1,size do
    print(array[i])
end

The code above was meant to generate an array of random numbers from 1 to 'size' avoiding repeating values. I tried to achieve that by repeating top level 'for' loop once more if newly generated value was present before somewhere in array - by decreasing its iterator. Somehow it doesn't work. Why?

Is modifying iterator value from inside of loop not possible?

Example output with repeating values in array:

>lua5.1 "pairsss.lua"
2
1
10
6
5
2
5
7
7
4
>Exit code: 0

Solution

  • The solution to your problem is to shuffle the array, like Random iteration to fill a table in Lua.

    To answer your question, from Lua 5.1 reference manual:

    §2.4.5 – For Statement

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

    That means, no matter how you change the value of i inside the for loop, it doesn't affect how the iteration is done.