There are two types of tables: indexed with a number (Arrays) and indexed with a key (Key-Value pairs). Randomizing key-value pairs makes no sense. There is no implied order. You get the key when you get the key. However when indexing using numbers, being able to access those values randomly is quiet common.
There are two ways to access table data randomly: 1. Where any table member can come up multiple times or 2. Where each value gets used only once. This second mode is known as shuffling.
In the first mode, you can just generate a random number between 1 and the table size and use that value to reference the table entry:
local myTable = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
local randomEntry = myTable[math.random( #myTable )]
However, many people only want to use a value one. To do that you shuffle the table (like a deck of cards):
local function shuffleTable(t)
local rand = math.random
assert(t, “table.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]
end
end
local myTable = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
local shuffledTable = shuffleTable( myTable )
Then you use each entry one at a time
local randomEntry = shuffledTable[1]
Rob