Is it possible to use math.random with names instead of numbers?

Hello devs!

The title pretty much sums it up but I was wondering if it’s possible to use math.random with names instead of numbers. For example, say I wanted to make a game idea generator. How would I put the names in there if it’s not a number? I just tried this is studio and the error message was that it wasn’t a number. Obviously, when using the random function, you would put the two numbers. But is it possible to to use it with names instead?

Thanks for reading! :slight_smile:

Use a table to store the names.

local namesTable = {'Name', 'Name2', 'Name3', 'Name4'};
print(namesTable[math.random(#namesTable)]) --// this does not work for dictionaries!
1 Like

Yes that is possible, by choosing a random index, to correct @WhitexHat’s code it should be more like this:

local namesTable = {'Name', 'Name2', 'Name3', 'Name4'};
print(namesTable[math.random(1,#namesTable])

math.random requires 2 arguments - these arguments are the range - @WhitexHat only specified 1 argument, therefore it won’t work at all or not properly.

3 Likes

You should correct yourself then.

When called with an integer number m, math.random returns a uniform pseudo-random integer in the range [1, m]

Run the code and you’ll see.

1 Like

Yeah you might be right, I’ve never run code that uses math.random like that :grinning:.

He was right originally… Your correction was incorrect :neutral_face:

I think he might be right, tho I have never tried that method, my code I’d say is the long-form of his code.,