SRAND


srand( seed )
s (seed) a number to use as a seed value
rand "random"

The srand() function is used to seed the random number generator: rnd(). In computer programming, a random number generator is not truly random, it is actually a deterministic algorithm that produces a sequence of seemingly random numbers. Every time a PICO-8 cart runs, the rnd() function uses a different seed value to begin generating its sequence of numbers.

By providing a seed value to srand(), you can control and reproduce the same sequence of random numbers.


For example:

--random every time
print( rnd(10) ) --unpredictable
print( rnd(10) ) --unpredictable
print( rnd(10) ) --unpredictable

--seeded random
srand(5)
print( rnd(10) ) --3.6121
print( rnd(10) ) --7.4159
print( rnd(10) ) --9.0311

--same seed, same results
srand(5)
print( rnd(10) ) --3.6121
print( rnd(10) ) --7.4159
print( rnd(10) ) --9.0311

This could be used with a random level generator to reproduce the same level or sequence of levels in your game.

Since rnd() can also be used to get values from tables at random, you can use srand() to make the table value selection more predictable and in a specific sequence.

table = { "a", "b", "c", "d" }

--random
print( rnd(table) ) --unpredictable

--seeded random
srand(5)
print( rnd(table) ) --a
print( rnd(table) ) --c
print( rnd(table) ) --d

--same seed, same results
srand(5)
print( rnd(table) ) --a
print( rnd(table) ) --c
print( rnd(table) ) --d


532

19 Aug 2023

Font