RND


rnd( a )
rnd "random"
a a number or table

The rnd( a ) function is used to return a random number within the range of 0 up to but not including the number given.



Get Random Number

For example:

a = rnd(5)    --range: 0-4.9999
b = rnd(20)   --range: 0-19.9999
c = rnd(500)  --range: 0-499.9999

To get a random integer (whole number) use flr() with rnd() like this:

d = flr( rnd(10) )  --range: 0-9 integers

--shorthand floor
e = rnd(10)\1      --range: 0-9 integers


Get Random Table Value

You can also pass a table to the rnd() function to get a random value from the table:

table = { 4, 6, 8, 10 }

rnd(table)  --4, 6, 8, or 10

The table must have numbered keys because the function will find a random integer between 1 and the total count of the table and return the value stored at that table index. There is also a shorthand of providing the table itself in replace of the parentheses:

table={ 1, 3, 4, 10 }

--longform
table[ 1 + flr( rnd(#table) ) ]

--shorthand
rnd{ 1, 3, 4, 10 }

This can be useful for specifying a list of certain possible values, such as the spawn zone of an enemy, or the color numbers of a rectangle:

colors = { 8, 9, 12, 1, 4 }

rectfill( 40,50,60,70,rnd(colors) )  

Notice that the color numbers in the table can be in any order. 


Images in this Guide by NerdyTeachers is licensed under CC BY-SA 4.0

825

12 May 2023

Font