random package

random contains no utilities.

License

The random package is marked as Compatible, which means any game can use it.

Classes

RNG

An instance of RNG encapsulates a stream of random numbers. Any two RNGs of the same type initialized with the same seed(s) will give the same sequence of random numbers on all platforms.

If this package is installed, SubCritical replaces Lua's math.random and math.randomseed functions with equivalent versions that use the "best" available RNG instead. (The starting random seed is a single 1.)

rng = SubCritical.Construct("RNG", seeds...)
seeds is a sequence of one or more integers. Each will be both clamped to the range [0,4294967295] and rounded to a nearby integer in an undefined way. (For maximum compatibility, provide only numbers that will not be changed by either operation.)
One could use a text string as a random seed like so:
function bytes(str)
  local ret = {}
  for char in str:gmatch(".") do
    ret[#ret+1] = char:byte()
  end
  return unpack(ret)
end
-- ...
rng = SC.Construct("RNG", bytes(my_string))
Note that if you are hoping to get the same sequence of random numbers at both ends of a network socket (even if both ends are the same platform), you should Construct a specific type of RNG. For example, construct a generic RNG at the server end and use rng:Identity() to transmit its class for specific instantiation at the client end. (Or just construct SFMT19937 directly instead.)
number = rng:Random()
Returns a random number such that 0 <= number < 1.
number = rng:Random(max)
Returns a random integer such that 1 <= number <= max. If max <= 1, this will return 1.
number = rng:Random(min, max)
Returns a random integer such that min <= number <= max. If either min or max < 0, or if min-max < 1, this will return the smaller of its two parameters.

SFMT19937 : RNG

SFMT19937 is a interface to the reference implementation of Mutsuo Saito's and Makoto Matsumoto's SIMD-oriented Fast Mersenne Prime Twister with a period of 219937-1. (This is a VERY big number, so this is likely to be sufficient for any SubCritical games.) It has good statistical properties, and good performance. The adventurous may try their hand at compiling the included AltiVec- or SSE2-enabled codepaths. (The machine this package was developed on is capable of neither.)

rng = SubCritical.Construct("SFMT19937", seeds...)

Back to index