- Generates a random number between 0 and the given maximum.
- max
- The range, non-inclusive.
The rnd()
function returns a random number in a range. The result ranges from 0 up the given max
, but will never be the max
value itself. For instance, rnd(10)
can return from 0 up to 9.99999, but will never return 10.
The random number includes a fractional part. To get a random integer, use flr(rnd(max))
.
The random number generator is initialized with an unpredictable seed value when PICO-8 starts. You can reinitialize the generator with an explicit seed (such as to test random behaviors with a known sequence) using srand().
Working with ranges Edit
To select a random number between a minimum and a maximum, call rnd()
with the size of the range, then add the minimum:
x = rnd(32) + 64 -- a random number between 64 and 96 scale = rnd(20) - 10 -- a random number between -10 and 10 die = flr(rnd(6)) + 1 -- a random integer between 1 and 6
To select a random fraction with a fixed number of decimal digits, use flr(rnd(...))
with the range times the precision, then divide by the precision:
earnings = flr(rnd(50 * 100)) / 100 -- between 0.00 and 50.00
Alternate ranges Edit
rnd()
called with a negative value for max
returns a random value in the range of all numbers, from -32768.0 (0x8000.0000) up to +32767.99999 (0x7fff.ffff).
rnd()
called without a max
value (nil
) returns a random value in the range from 0.0 up to 0.99999 (0x0.ffff).
rnd()
appears to accept a negative max
value, treating the number as if it is unsigned when it computes the range for the output, thus the result may overflow the range and wrap to negative.
Examples Edit
print(rnd(20)) -- for example, 3.837 print(flr(rnd(20))) -- for example, 17 -- note this is the same as rnd(0xffff) print(rnd(-1)) -- for example, -1734.56 or 13744.63