Math.random() returns same number every time after a delay from setting randomseed

I look at this as independent. We could provide a custom PRNG module - however, it won’t help people who are already using math.random() (which unfortunately is a builtin in Lua). Plus if you really want good random numbers you can just write a PRNG yourself :slight_smile:

So ideally I’d rather fix math.randomseed first, and then if there is still demand for instance-based RNG add that. This is why I’m thinking of scripts as units of isolation - it’s pretty commonplace in ROBLOX, with globals separation etc.

The problem with option 1 is that any other script calling math.randomseed will reset your RNG state. Here’s the issue I ran into some time ago:

I had code like this:

for i=1,100 do
    local npc = Zombie:Clone()
    local x = (math.random() * 2 - 1) * 100
    local z = (math.random() * 2 - 1) * 100
    npc:SetPrimaryPartCFrame(CFrame.new(x, 10, z))
    npc.Parent = workspace
end

All zombies were spawned in the same place, which took me some time to figure out. The problem was that the NPC model had a script that called math.randomseed(os.time()) in it upon startup. What happened is that every time I parented the new model to the workspace, the script ran and reset the randomseed; since os.time() value did not change between invocations since the loop is pretty fast the seed was always reset to the same number at the end of every iteration, and I got the same x/z values on every iteration.

5 Likes

Setting the script as the environment could work to enforce determinism which is my main concern with random numbers. I’m still interested in the idea of a new type or instance so we can support different distribution types or algorithms (although I suppose we could just use setter functions for those).

Could we have it set the seed per lua stack?

I feel that if we were to introduce new RNG APIs we’d definitely go with object-based API - implicit global state is pretty bad no matter how we slice it. That is, I’d rather have new API, than extend Lua’s math.random()/randomseed() - the only reason I’m even suggesting fixing math.random/randomseed is because a lot of people know it and use it.

1 Like