tags:

views:

88

answers:

2

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

+1  A: 

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

ShinTakezou
+6  A: 

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.

MiKy