switch

In a number of situations you want to let your instances complete different actions depending on a particular value. You can do this using a number of consecutive if / else statements, but when the possible choices gets above two or three it is usually easier to use the switch statement. A switch statement has the following form:

switch (<expression>)
{
    case <constant1>: <statement1>; ... ; break;
    case <constant2>: <statement2>; ... ; break;
    ...
    default: <statement>;
}

This works as follows:

A simple example of using a switch statement would be something like this:

switch (global.state)
{
    case "alert":
        if (instance_exists(obj_Player))
        {
            if (point_distance(x, y, obj_Player.x, obj_Player.y) < 100)
            {
                global.state = "chase";
            }
        }
    break;
    case "chase":
        var _lost = false;
        if (instance_exists(obj_Player))
        {
            move_towards_point(obj_Player.x, obj_Player.y, 2);
            if (point_distance(x, y, obj_Player.x, obj_Player.y) > 100)
            {
                _lost = true;
            }
        }
        else _lost = true;

        if (_lost)
        {
            speed = 0;
            global.state = "alert";
        }
    break;
}

Here we have a global variable that holds a string value which is used to set the behaviour (state) of the instance. In this example the instance simply switches between two states, but it is extremely easy to expand this to include more states by adding further case statements for additional state strings, like "fight" or "die", etc...

Note that multiple case statements can be used to execute the same statement, as the break is not always required for each and every case. If there is no break statement for a particular case, the execution simply continues with the code for the next case, eg:

switch (keyboard_key)
{
    case vk_left:
    case ord("A"):
        x -= 4;
    break;

    case vk_right:
    case ord("D"):
        x += 4;
    break;

    case vk_up:
    case ord("W"):
        y -= 4;
    break;

    case vk_down:
    case ord("S"):
        y += 4;
    break;
}

The above code uses switch to check for a keyboard event and then compares that to each case listed. If it meets any of the required values then the corresponding code is executed. Note how in the code we have used the way that switch can check multiple cases and continue if no break is encountered to permit various keys to be used to get the same result. Note that each case can have it's own code, and so you can set up a sort of "inheritance" system where more than one case and it's code will run consecutively with the next until a break is reached depending on the value of the initial switch expression.