[Updated July 31, 2020]
There are many times when I need a random true or false in my code. Maybe I want to show the red spaceship some of the time and the blue spaceship the rest of the time. So I created a coinToss() function that gives me back a random true or false. It looks like this:
1 2 3 |
local function coinToss() return math.random(2) == 1 end |
Now I can write code: if coinToss() then foo.
But every once in a while I need a weighted “random” answer. For example, I want the red ship 75% of the time and the blue ship the rest. So I created a better coinToss() function — this one has two lines of code instead of just one. But it allows an optional parameter to specify what percentage you want to be true.
1 2 3 4 |
local function coinToss(weighted) local w = weighted or 50 return math.random() <= w/100 end |
If I want something to happen 63% of the time, I can call it like this:
1 2 3 |
if coinToss(63) then -- do something here 2/3 of the time end |
If all I want is the random true/false, I can skip passing in the parameter and get that back.
The coinToss() function finds its way into just about all my projects. If you don’t have your own library of routines you use over and over, grab coinToss() and use it as a starter for your own set. š
Previously posted for CoronaSDK, this is also valid for Solar2D.