Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Random name Function?

Asked by 10 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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

0
That didn't help me or do anything, sorry :l BritishParliament 0 — 10y
0
Nevermind it did, thanks for the help BritishParliament 0 — 10y
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 BlueTaslem 18071 — 10y
2
Can't you leave out the first argument, and just put math.random(#names)? Thewsomeguy 448 — 10y
0
Thewsomeguy: Yes, you're right! I didn't know that. I think the explicit first argument is much clearer, though and simplifies understanding BlueTaslem 18071 — 10y
Ad

Answer this question