Tutorial about Random object

by Aceriterium

Author Avatar

1. What is Random.new()? Isn't there math.random() already?

Random.new() is a new roblox object that is different from already existing math.random().

While math.random()'s and Random.new()'s functionalities are the same, Random.new() allows you to have

multiple random number generators with different seeds.

2. How to use Random.new() object?

First off, create a Random via Random.new() (obvious, right?)

local rng = Random.new()
local seed_rng = Random.new(1234)
local another_seed_rng = Random.new(1234)

The first argument in Random.new() (The number) is the seed. The seed is what determines what you get. So even if you use Random.new() two times, if they are created with the same seed, it will return the same result in sequence.

You can leave it blank for random 'random number generators'. So how do you get numbers from it? Simple; Use :NextInteger() and :NextNumber() :

print(rng:NextInteger(1, 10)) -- 5 (Single integer ranging from 1 to 10)
print(seed_rng:NextInteger(1, 10)) -- 4
print(another_seed_rng:NextInteger(1, 10)) -- 4

print(rng:NextNumber()) -- 0.429301940584 (Single number ranging from 0 to 1)

The first and second arguments in :NextInteger() is the range; For example, on the example above,

rng:NextInteger(1, 10) will return numbers ranging from 1 to 10. :NextNumber() doesn't include any arguments, however,

will return numbers with decimals ranging from 0 to 1.

3. Wait, but I need some number ranging from one to another with decimals. How can I do that?

It is a pretty easy task to do! You will need some maths, however :

local a = -5
local b = 10

print(a + rng:NextRandom() * (b - a)) -- 7.59285931842 (Single number ranging from -5 to 10)

Here, a is start and b is end of the range. The multiplication extends decimal number ranging from 0 to 1 to difference of a to b,

Which is a size of range we want. (In this case, 15.) And after multiplication, it adds start, which is a, and broughts down (or pulls up)

the range to -5 to 10, which was 0 to 15.

4. Is there any way to Clone it?

Yes :

local another_rng = rng:Clone()

print(rng:NextInteger(1, 10)) -- 7
print(another_rng:NextInteger(1, 10)) -- 7

View in-game to comment, award, and more!