Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose a random item from a table

Tags:

random

lua

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', 'c', 'd' } print( myTable[ math.random( 0, #myTable - 1 ) ] ) 

How can I fix the above code so that it works as intended? (Or which other method could I use?)

like image 520
Zen Avatar asked Jun 07 '10 09:06

Zen


1 Answers

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.

like image 84
Michal Kottman Avatar answered Sep 21 '22 15:09

Michal Kottman