Corona SDK and other Game Development Tutorials

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
 return t

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.

  1. Hello, thanks for the tutorials,I want to you a question, Im working in a game, I have to remove many objects, touching a bomb, but I cant make it work.
    can you teach me a method please.
    greetings from peru

    • Hello! I’ve sent you an email so we can talk directly.

Leave a Reply