My goal is to pick out a random item from a table in Lua.
This is what I\'ve got so far, but it currently does not work:
local myTable = { \'a\', \'b\',
I think the question also needs a more general answer. There is no limitation on lua tables to be built with a sequence of integers starting from 1. Keys can be really anything - they could even be other lua tables! In such cases, functions like #myTable might give an answer you don't expect (when used without any custom metatable functionality). The only reliable way to get all keys in a table is to iterate over it:
-- 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)]]
I will also add that the original solution by Michal Kottman would work perfectly if all your keys are a sequence of numbers starting from 1. This happens whenever you create a table as myTable = {'a','b','c'}
. So for situations where tables are built this way, getting random elements from the table would be faster his way.