Yeh ok so Elvish's code is a little off… here is a better example (similar to MysticT's)
local myTable = {12, 45, 76, 23, 68, 34}
local randNum = math.random(#myTable) --# the same as math.random(1, #myTable)
print(myTable[randNum])
The reason your first method doesn't work is because
math.random wants numbers, a table is not a number.
The reason your second method doesn't work is because it first calculates the math
1-5 which is
-4 and there is not entry in the table at the index
-4The reason that Elvish's doesn't work is, well, lots of reasons, basically its just not what you want/need.
The difference between MysticT's and mine is that mine does not have the non-required first argument of 1 in the math.random, when this argument is not supplied 1 is assumed.
Now how the code example I provided works is that
math.random is told to supply you with a random number between 1 and the amount of values in the table. This can then be used as it is a valid index for that table.
There is one time however where the above code example would fail, and that's when you have a table like so
local myTable = {1, 2, 3, [5] = 5, [6] = 6}
and the reason this fails is that it is non-sequential, there is no element in the 4th index, thus meaning that the # operator will tell you that there's only 3 elements, instead of 5… Obviously there will also be a problem with key/value pairs such as
["foo"] = 7. A solution to the above problem would be as follows
function table.random( tbl )
local keys = {} --# lets make a copy of all the keys in the table
for k in pairs( tbl ) do --# we have to use pairs as ipairs will have the same problem as # and stop when it hits the end of a sequential index
if type(k) == "number" then --# lets only care about numbers, you can remove this if you also want to include the entries such as ["foo"] = "bar"
table.insert(keys, k) --# put the key into the table
end
end
--# now we have a table containing all the index keys, lets pick a random key from that table
local randIndex = math.random(#keys)
local randKey = keys[randIndex] --# this is now the key for a random entry that's in our original table
return tbl[randKey] --# returning the value from the original table using the key that we just randomly picked
end
As you can see the above code example is much more complicated, but it allows us to work with any table that has number values (and with slight modification any value) and return it, no matter the order or index of the index/key.