Page 1 of 1

random numbers in _post

Posted: 11 Oct 2015, 12:31
by Silentwings
_post files don't offer math.random, but sometimes you want it.

What follows is a bad random number generator that should not used be used in any circumstances. If all you want to do is generate random RGBA colours or something, you obviously shouldn't use it, but you might decide to use it anyway because you're too lazy to write anything better, in which case...

Code: Select all

local _m = 3*3*113 -- 1017
local _a = 3*113 + 1
local _c = 5*5*5*7
local _seed = 1 
local _x = _seed
local _gen = 0
local function rand()
    -- advance seed when we finish each cycle 
    _gen = _gen + 1
    if _gen >= _m then
        _seed = _seed + 1
        _gen = 0
        if _seed >= _m then
            _seed = 1
        end
        _x = _seed
    end

    _x = math.floor((_x*_a + _c) % _m)
    return _x/_m
end
local function Random(n,m)
    if n==nil then return rand() end        
    m = m or 1
    return m + math.floor(rand()*(n-m))
end
math.random = Random
Seed it with a modoption, unless you can think of a better way. Off the shelf lua RNGs will typically go dolalalala in Spring because single precision. At least this one won't do that. It will also behave reasonably well when you stripe it over an array of RGBA values i.e. with periodicity 4.