A (very) simple random number generator written in plain TorqueScript which allows you to create however many private, separate-state generators as you need.
When it comes to randomness? It's random "enough" for anything you'll need to do in Blockland. Just don't use it for bank-level cryptography and you're fine.
UsageTo create a new RNG state, call
createRandContext([seed]). This will return a new "generator handle" which you can pass to all the other functions to use it. The generator will, by default, use the current platform time as the initial seed unless you explicitly pass an alternative using the
seed argument.
%context = createRandContext();
echo(rand(%context)); // 0.150304, for example
echo(rand(%context, 5)); // 3.11251, for example
echo(rand(%context, 100, 200)); // 138.01, for exampleGet/set the seed using
getRandSeed and
setRandSeed. For example:
setRandSeed(%context, 64);
echo(rand(%context, -10, 10, 0)); // -6
echo(rand(%context, -10, 10, 0)); // 4
echo(rand(%context, -10, 10, 0)); // -1
echo(rand(%context, -10, 10, 0)); // 0
echo(rand(%context, -10, 10, 0)); // 6
// set the generator back to it's initial value
setRandSeed(%context, 64);
// exact same sequence
echo(rand(%context, -10, 10, 0)); // -6
echo(rand(%context, -10, 10, 0)); // 4
echo(rand(%context, -10, 10, 0)); // -1
echo(rand(%context, -10, 10, 0)); // 0
echo(rand(%context, -10, 10, 0)); // 6Function ReferencecreateRandContext([seed])Returns a numeric "generator handle" which can be passed to other functions.
If
seed is omitted, it defaults to
getRealTime().
Note: This does not create an object. You don't need to clean up by deleting anything.rand(context, [min], [max], [precision])Returns a random number generated using the given context. If given,
precision will round the result before returning. Use 0 if you want integer values. This function has the following signatures:
rand(context)
Returns a random floating point number from 0 to 1, inclusive.
rand(context, x)
Returns a random floating point number from 0 to x, inclusive.
rand(context, a, b)
Returns a random floating point number from a to b, inclusive.
rand(context, a, b, c)
Returns a random integer or floating point number from a to b, inclusive, rounded to precision digits.getRandSeed(context)Returns the initial seed value of the given generator context.
setRandSeed(context, seed)Sets the initial seed value of the given generator context to
seed and sets its state back to it.
Sourcehttps://gist.github.com/portify/7403514 (37 LOC)