Math.random reusing same values?

Hi all,

I’m currently trying to create a factory that will randomly set the locations of the created objects. I’ve tried two methods to create these random values. One of them makes each value different, and the other results in all three values being the same random number.

math.randomseed(os.time())
factory.create("/worm_spawner#worm_factory", vmath.vector3(250,250,1), nil, { local_pos = math.random(-75, 75), bool = math.random(0, 1)}, .25)
factory.create("/worm_spawner#worm_factory", vmath.vector3(200,200,1), nil, { local_pos = math.random(-75, 75), bool = math.random(0, 1)}, .25)
factory.create("/worm_spawner#worm_factory", vmath.vector3(550,400,1), nil, { local_pos = math.random(-75, 75), bool = math.random(0, 1)}, .25)

V1: all three local_pos values are the same

math.randomseed(os.time())
x1 = math.random(-75, 75)
x2 = math.random(-75, 75)
x3 = math.random(-75, 75)
factory.create("/worm_spawner#worm_factory", vmath.vector3(250,250,1), nil, { local_pos = x1, bool = math.random(0, 1)}, .25)
factory.create("/worm_spawner#worm_factory", vmath.vector3(200,200,1), nil, { local_pos = x2, bool = math.random(0, 1)}, .25)
factory.create("/worm_spawner#worm_factory", vmath.vector3(550,400,1), nil, { local_pos = x3, bool = math.random(0, 1)}, .25)

V2: all three local_pos values are different

My best guess is that the program is calculating one random value with the given parameters and using it for all the instances where it’s called. Is there any way to make the first version work? (I’d like to use loops in the final version of this). Thanks!

You have to throw away the first one or two random numbers.

math.randomseed(socket.gettime()) 
math.random() 
math.random()
math.random()

I don’t understand how that relates to this. In both of these cases, I’m generating the same amount of random numbers, I’m just changing when I do it and how I use them, and getting different results.

I think maybe in the first case math.random() is being passed inside the table to the factory function; when the table element is accessed it is run, in this name-space math.random( os.time()) has not been run, resulting in all the values being the same.

This should no longer be needed. We fixed that quite some time ago

1 Like

You should only call this function once when your program starts. Are you calling it multiple times?