Hey everyone,

In observance of the gift-giving season, we’re releasing a new Lua datatype: Random.

Random is used to generate high-quality pseudorandom numbers from a dedicated internal state.

API

Random.new([double seed])

Creates a new Random object from the given seed.

Multiple Randoms seeded with the same value will always produce the same number sequence.

If a seed isn’t specified, one will automatically be pulled from an internal entropy source.

int Random:NextInteger(int min, int max)

Returns a pseudorandom integer uniformly distributed over [min, max].

double Random:NextNumber([double min=0, double max=1])

Returns a pseudorandom number uniformly distributed over [min, max).

Random Random:Clone()

Returns a new Random object with the same state as the original.

This method can be useful for branching off the results of the RNG.

Technical details

The algorithm used by Random is the XSH-RR variant of the PCG family.

In a nutshell, it’s is a fast algorithm with excellent statistical properties.

We’re planning to change math.random to use the same algorithm by early next year.

Examples

Flip a coin

local rng = Random.new() local function CoinFlip() return rng:NextNumber() < 1/2 and 'Heads' or 'Tails' end

Shuffle an array

local rng = Random.new() local function Shuffle(t) for i = #t, 2, -1 do local j = rng:NextInteger(1, i) t[j], t[i] = t[i], t[j] end end

Generate a random color

local rng = Random.new() local function RandomColor() local r = rng:NextNumber(0, 255) local g = rng:NextNumber(0, 255) local b = rng:NextNumber(0, 255) return Color3.fromRGB(r, g, b) end

Feel free to post questions and comments; our team would love to hear your feedback.

This is live. Happy holidays!