Choose a random item from a table
snippet in lua

Choose a random item from a table

user6783

print( myTable[ math.random( #myTable ) ] )

Choose a random item from a table

user8486

-- iterate over whole table to get all keys
local keyset = {}
for k in pairs(myTable) do
    table.insert(keyset, k)
end
-- now you can reliably return a random key
random_elem = myTable[keyset[math.random(#keyset)]]