Using Shuffle with Lua

Sometimes you need to be able to randomize a table in your Corona SDK app (or any other platform that uses Lua). So, here’s how you do it.

local function shuffle(t)
  local n = #t
  while n > 2 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
    n = n - 1
 end
 return t
end

This function accepts one argument, a table, and then proceeds to randomize the elements of the table. It randomizes the elements of the table by making use of the math.random tool.

Now, I can’t claim credit for creating this shuffle function, but I wanted to post it for other developers use. If you know who the original developer is who created this function, please let me know and I will give due credit.

Leave a Reply

Your email address will not be published. Required fields are marked *