Question

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
Was it helpful?

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.

OTHER TIPS

You can use a set instead of an array, as done by the author of question Randomize numbers in Lua with no repeats. As one of the answers points out, as your set gets closer in size to your range of randome numbers (say, you have random numbers 1 to 100 and your set is size 50) it will be more and more difficult to find a number that hasn't already been picked. You can see that for a set of size 50 and picking a random # from 1 to 100, then by the time you have the set half full, you have a 25-50 % chance of finding the random pick is already in use in your set. In that case, shuffling is the way to go, as explained in one of the answers to that post (Randomize numbers in Lua with no repeats).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top