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\',
Test:
t = {'a', 'b', 'c'}
print(t[0])
gives nil
. In fact 0 is out of bounds (try t[20]
)... so random must be from 1 to #myTable
(inclusive) because the first element of a table is labeled (indexed) as 1 if you write just exp
, see Table constructor ("Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive integers starting with 1.").
If you pass to math.random just an argument n
, you obtain a random number from 1 to n
inclusive. This fixes your example:
print(myTable[math.random(#myTable)])