Test:
t = {'a', 'b', 'c'}
print(t[0])
gives nil
. That is,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
, sosee Table constructor ("Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive integers starting with 1.").
If you can fix it by yourselfpass 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)])