Skip to main content
do not let OP or readers try to deduce anything: they just want a ready and educational answer
Source Link
ShinTakezou
  • 9.6k
  • 1
  • 31
  • 40

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)])

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20])  ... so random must be from 1 to #myTable (inclusive), so you can fix it by yourself.

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)])
answer was misleading
Source Link
Claus Wilke
  • 17.6k
  • 8
  • 58
  • 106

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]) ... so random must be from 1 to #myTable  (inclusive), so you can fix it by yourself.

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]) ... so random must be from 1 to #myTable(inclusive), so you can fix it by yourself.

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]) ... so random must be from 1 to #myTable  (inclusive), so you can fix it by yourself.

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]t[20]) ... so random must be betweenfrom 1 andto #myTable(inclusive), so you can fix it by yourself.

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]) ... so random must be between 1 and #myTable, so you can fix it by yourself.

Test:

t = {'a', 'b', 'c'}
print(t[0])

gives nil. That is, 0 is out of bounds (try t[20]) ... so random must be from 1 to #myTable(inclusive), so you can fix it by yourself.

added 4 characters in body
Source Link
ShinTakezou
  • 9.6k
  • 1
  • 31
  • 40
Loading
Source Link
ShinTakezou
  • 9.6k
  • 1
  • 31
  • 40
Loading