Log In  


These are variations of the rnd() function, but these return integers. You can either give just a maximum value or an arbitrary minimum and maximum value. You can also choose whether you want the maximum value to be exclusive or inclusive.

--random int between 0,h
function rand(h) --exclusive
	return flr(rnd(h))
end
function randi(h) --inclusive
	return flr(rnd(h+1))
end

--random int between l,h
function randb(l,h) --exclusive
	return flr(rnd(h-l))+l
end
function randbi(l,h) --inclusive
	return flr(rnd(h+1-l))+l
end
9


1

Thank you! This was really helpful.


Excellent stuff @MBoffin - will definitely save having to think this out every time (and no-doubt fixing bugs coz I won't get it right first time!).
Thanks buddy! ;-)


1

Ha, wow. This is really old. :D Now that it's been about 2 years (!) since I posted this, I can honestly say the one of these four that I use the most by far is the inclusive random integer function. To the point where that's often the only variation I'll put in my code.

Glad these were useful. :)


May I publish some or all of your code, or derivatives, in https://github.com/sparr/pico8lib ?


@sparr Go for it.


2

Hi @MBoffin. Gold star for this information !

Here is a variation I use that ensures no matter the order the input, you still get the correct results.

-- return random # from a to b
function rand(a,b)
  if (a>b) a,b=b,a
  return a+flr(rnd(b-a+1))
end--rand(..)

INPUT: two numbers
RETURNS: integer number including and between both numbers.
USES:
print rand(1,6) ... dice
print rand(1,52) ... pick a card
print rand(9,-4) ... will pick # including and between negative 4 and positive 9.


Thanks! Super helpful



[Please log in to post a comment]