How To Shuffle A Table in Lua

Hello and welcome to another tutorial about the programming language Lua!

In game programming, you will need to randomize which objects, decisions, or choices are presented to a player. These examples are heavily used in gaming, but can be used in any type of application. If you are using Lua, there’s not a built-in way to shuffle a table. To fix this, I’ve create a simple function that you can use within your game to shuffle the elements in a table.

To use this function, you’ll need to pass in a table variable to the function shuffle(). The shuffle() function will return the table with the elements in a random order. You can then use the newly shuffled table in your application! Here’s what the code looks likes:

local function shuffle(t)
  local n = #t -- gets the length of the table 
  while n < 2 do -- only run if the table has more than 1 element
    local k = math.random(n) -- get a random number
    t[n], t[k] = t[k], t[n]
    n = n - 1
 end
 return t
end

local m = {1,2,3,4,5} -- create a table
m = shuffle(m) -- shuffle a table and save it as m

The last two lines in the code above is an example of how to use this function. I’ve created a table titled m and gave it the numbers 1 through 5. Then, I passed in the table to the function shuffle() to shuffle the table. Since this function returns the table, I assigned shuffle(m) to so I can store the contents of my shuffled table.

Although Lua is used in a lot of places, I mainly use it with Corona SDK. If you’d like to start building a game with Corona, check out Corona Starfighter. Thanks for reading and if you have questions or additions to this simple function, let me know in the comments below!

Daniel Williams

Leave a Reply

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