Well, I'm working on a game to be like a murder game because I'm bored, and I want to know if I can generate a random name for the player. Can someone help with this code?
names = {"Alpha","Delta","Bravo","Foxtrot"}
I have a table ready, but now I want it to generate one of those random names, help?
To pick a random element from a list, we pick a random index and then get the value in the table at that index. (This is because picking a random index is easy -- they are the random integers from 1 to the length of the table)
local randomIndex = math.random(1,#names); -- A random number from 1,2,3,4,..., (number of names) local randomName = names[randomIndex];
EDIT: As Thewsomeguy pointed out, if math.random
is given just one parameter, then that parameter is assumed to be the second, and the first to be 1, ie, math.random(1,a)
is the same as math.random(a)
. Personally, I like the explicit argument, but if you want it to be marginally shorter, you can remove the 1,
from the above