- Joined
- Jan 1, 2011
- Messages
- 1,532
Very useful if you need randomness that is async.
Lua:
do
RNG = {seed = 0, mult = 1140671485, mod = 16777216, inc = 12820163}
--[[
Default RNG values with a seed of 0. You can initialize a new RNG
class with just the seed if you don't want to change the rest of the
values.
API:
Class: RNG
Arguments:
seed - initial seed of the RNG table
mult - multiplier value
mod - modulo value
inc - increment value
Example:
rng = RNG:new({
seed = math.floor(os.clock()*100000),
mult = 1140671485,
mod = 16777216,
inc = 12820163
})
To access the RNG class we have just created, call the table:
rng() -- no arguments is a range betwee 0 and 1
rng(100) -- only 1 argument means a range 1 - val (1-100 in this case)
rng(5.0,25.0) -- two arguments means a range from low - high (int or float)
]]--
function RNG:new(tbl)
tbl = tbl or {}
setmetatable(tbl,RNG)
tbl.div = 1/tbl.mod
return tbl
end
function RNG.__index(tbl,key)
return RNG[key]
end
local d, m
function RNG:__call(low,high)
d = self.seed * self.mult + self.inc
m = d - math.floor(d * self.div) * self.mod
if m < 0 then
m = m + self.mod
end
self.seed = m
m = m * self.div
if low then
if high then
m = m*(high-low)+low
else
m = m *(low-1) + 1
end
if math.type(low) == "integer" then
m = m>=0 and math.floor(m+0.5) or math.ceil(m-0.5)
end
end
return m
end
end
Last edited: