Corona tip: Shuffle it!

December 26, 2012 at 9:44am

Need to pick something randomly but make sure it gets used only once? Shuffle it!


local function shuffle(t)    

local rand = math.random    

assert(t, "shuffle() expected a table, got nil")    

local iterations = #t     local j        


for i = iterations, 2, -1 do        

j = rand(i)    

  t[i], t[j] = t[j], t[i]    




numbers = {1,2,3,4,5,6,7,8,9,10,11,12} -- say up to 52 if your're doing a card game   




Then simply loop over the table from 1 to #numbers and you have a randomly sorted array of entries. It doesn't have to be numbers either. It could be images you want to use randomly, a bunch of audio handles for sound tracks you want to shuffle and play.