phpInDev

random_int

int random_int ( int number1, [ int number2, [ bool exclusive ] ] )

This script returns a random integer between number1 and number2. It doesn't matter whether they are negative numbers or not or whether first is bigger than the second. The random number is always between the two given numbers. By default, the random number is inclusive (the limits are included), however if exclusive is specified as true, the border numbers are not included within the random numbers. Note that you don't necessarily need to define the second number, as then a number between the given number and 0 is returned (inclusive).

NOTE: If you specify exclusive random number and the limits are either the same number, or next to eachother, 0 is always returned (because the limits are invalid).

NOTE: Despite al the weirdness in GM's random function, this function will make sure that no odd values are returned. In case the function attemps to return an invalid value, a new random number is generated instead.

Example 1. Using random_int

{ show_message("Lucky number is " + string(random_int(0, 10))); }

That could for example show:

Lucky number is 10

Code for random_int.gml

{
    var retval, mini, maxi;
    
    // Make sure if we have integers
    mini = floor(min(argument0, argument1));
    maxi = floor(max(argument0, argument1));

    // Make limits more narrow, if exclusive wanted
    if (argument2)
    {
        // Return 0, if invalid exclusive limits
        if (maxi - mini < 2)
        {
            return 0;
        }
        
        mini += 1;
        maxi -= 1;
    }
    
    // Make sure random doesn't do funny stuff
    do
    {
        retval = mini + floor(random(maxi - mini + 1));
    }
    until (retval <= maxi);
    
    return retval;
}