Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Random name Function?

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?

1 answer

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

5 comments

0

That didn't help me or do anything, sorry :l

0

Nevermind it did, thanks for the help

0

You can use the check mark to mark helpful answers as such, so that other people can find your question and see how it works

2

Can't you leave out the first argument, and just put math.random(#names)?

0

Thewsomeguy: Yes, you're right! I didn't know that. I think the explicit first argument is much clearer, though and simplifies understanding

This discussion is preserved as it was. New answers, comments, and votes are closed.