What is math.randomseed(tick())

I’ve seen math.randomseed(tick()) in many scripts and I was wondering what it exactly does and how it is useful. Any information is appreciated.

2 Likes

Sets the seed to tick(), which is time since 1970(?) in seconds. This prevents the results of math.random() from being the same across all servers.

Well, sort of. If you set the seed to the same number in all servers, you’ll get the same sequence of numbers with each subsequent call to math.random, however using tick will cause the results to be different, but they’re very close together

To give a fully detailed explanation, math.random uses a PRNG, or a pseudorandom number generator, which is an algorithm that outputs a sequence of numbers that exhibit the property of being random, but not genuinely. This algorithm takes an initial number, otherwise known as a seed, and the algorithm goes through its steps to output a “random” number. This random number is then used as the seed for the next subsequent call to math.random (if any) and the same goes on with each call to the function

So, if you set the seed to a number, for example 10, you’ll get the same sequence of numbers each time you call the function. For example:

math.randomseed(10)

for i = 1, 10 do
    print( math.random(1, 10) )
end

--[[
Printed:
7, 9, 10, 7, 1, 5, 9, 3, 1, 1
--]]

math.randomseed( 20 )

for i = 1, 10 do
    print( math.random(1, 10) )
end

--[[
Printed:
9, 8, 4, 4, 10, 8, 7, 6, 4, 3
--]]

math.randomseed(10)

for i = 1, 10 do
    print( math.random(1, 10) )
end

--[[
Printed:
7, 9, 10, 7, 1, 5, 9, 3, 1, 1
(Well, whad'ya know, it printed the same sequence of numbers when the seed was set to 10!)
--]]

I wouldn’t really use math.randomseed(tick()) in scripts for the aforementioned reason above

6 Likes

Totally correct. Thanks for elaborating.

On a side note: I find Random.new(tick()) inside a module a lot easier to use, and prevents issues where even tick() produces the same result if math.random() is called at the exact same time.

1 Like