Seems easy but I just don't get any further:
Take this example:
local myTable = { 'a', 'b', 'c', 'd' }
print( myTable[ math.random( 0, #myTable - 1 ) ] )
- Why doesn't it work?
Google seems to have no answers on this either
Seems easy but I just don't get any further:
Take this example:
local myTable = { 'a', 'b', 'c', 'd' }
print( myTable[ math.random( 0, #myTable - 1 ) ] )
Google seems to have no answers on this either
test:
t = { 'a', 'b', 'c' }
print(t[0])
gives nil. That is 0 out of bound (try t[20]) ... so random must be between 1 and #myTable, so you can fix it by yourself
Lua indexes tables from 1, unlike C, Java etc. which indexes arrays from 0. That means, that in your table, the valid indexes are: 1, 2, 3, 4. What you are looking for is the following:
print( myTable[ math.random( #myTable ) ] )
When called with one argument, math.random(n)
returns a random integer from 1 to n
including.