Unfortunately, Lua does not have any built-in implementation of shuffle algorithms.
However, there are some easy ones that you can implement or find.
The Fisher-Yates shuffle algorithm is an efficient, reliable, and easy-to-implement algorithm for array randomization.
Here is my optimized implementation of Fisher-Yates in Lua. Feel free to use it as you wish. All you have to do is put the function somewhere and call it on a table in array form that you want to shuffle.
01 | function shuffle(array) |
04 | local random = math.random |
06 | for index = 1 , #array do |
07 | local offset = index - 1 |
08 | local value = array [ index ] |
09 | local randomIndex = offset*random() |
10 | local flooredIndex = randomIndex - randomIndex% 1 |
12 | if flooredIndex = = offset then |
13 | output [ #output + 1 ] = value |
15 | output [ #output + 1 ] = output [ flooredIndex + 1 ] |
16 | output [ flooredIndex + 1 ] = value |
22 | math.randomseed(tick()) |