Is there a good way in Lua to randomize an array (or more particularly, pick indices in the array randomly)? To keep it simple, I have a table of strings that I want to display, but not in the same order every time. I was considering making a second table that stores whether I've used each index from the first array and just calling math.random() until it spits out an index that hasn't been used yet but this would get pretty bad when I start running out of unused indices. Anyone have a better idea?

Let's say t is your array containing the strings from t[1] to t[N] you want to randomize. To "shuffle" your array, do this:

[php]for i = N, 2, -1 do -- backwards
local r = math.random(i) -- select a random number between 1 and i
t[i], t[r] = t[r], t[i] -- swap the randomly selected item to position i
end[/php]Algorithm explanation:
On the 1st iteration, a random string between 1-N is swapped to position N.
On the 2nd iteration, a random string between 1-(N-1) is swapped to position N-1.
On the 3rd iteration, a random string between 1-(N-2) is swapped to position N-2.
...
On the last iteration, a random string between 1-2 is swapped to position 2.

Now that your array is shuffled randomly, you can just display them from t[1] to t[N].

I'm asuming you want to keep the same string around, just re-randomize them each time? Put them all in a table. Make a second, empty table. Pick one at random, use it, remove it for the first table and put it in the second. When the first table is empty, swap them, GOTO 10.

Essentially the same as Xin's, but might be easier to understand that the source set changes each time since the tables are separate.

[php]for i = N, 2, -1 do -- backwards

local r = math.random(i) -- select a random number between 1 and i

t[i], t[r] = t[r], t[i] -- swap the randomly selected item to position i

end[/php]

Algorithm explanation:On the 1st iteration, a random string between 1-N is swapped to position N.

On the 2nd iteration, a random string between 1-(N-1) is swapped to position N-1.

On the 3rd iteration, a random string between 1-(N-2) is swapped to position N-2.

...

On the last iteration, a random string between 1-2 is swapped to position 2.

Now that your array is shuffled randomly, you can just display them from t[1] to t[N].

Essentially the same as Xin's, but might be easier to understand that the source set changes each time since the tables are separate.

I'm not sure it'll be as efficient as Xinhuans, but if I understand how table.sort() and what your saying then it should work :P.

This won't work. table.sort would just error with an invalid sort function when it detects invalid situations (where a > b and b > c and c > a).