Skip to content
Tom Barham edited this page Sep 14, 2015 · 1 revision

Block statements are statements that contain a 'body', containing a list of statements, which are executed in a different pattern to normal execution.

When beginning development in MCA, it is important to remember that it is a macro language, and does not execute code at runtime. This means that you cannot use block statements as you would in a normal language (e.g. using the result of a command). Instead, you must use commands such as /testfor. The MCA common library has a useful .branch function which can be used to create dynamic statements.

if

The if statement allows code to be executed if a condition is true. It can be extended with an else statement, that is executed if the condition is false.

An if statement looks like this:

if (<condition>) {
    <body>
}

And an if/else statement looks like this:

if (<condition>) {
    <body>
} else {
    <else body>
}

If the condition evaluates to a truthy value (i.e a string with content, or a non-zero number), the main body will be executed. Otherwise, the else body will be executed.

If the body only consists of one statement, the curly braces can be removed:

if (<condition>) <statement>;
else <else statement>;

This allows us to use else if to provide multiple options:

if (<condition1>) {
    <body1>
} else if (<condition2>) {
    <body2>
} else if (<condition3>) {
    // etc
}

while

A while executes code in a loop until a condition becomes false. In the current version of MCA, this is the only looping statement apart from recursive calls.

while loops are similar to if statements: they have a condition and a body. The body will be executed again and again until the condition is false (or it will never be executed if the condition is always false).

while (<condition>) {
    <body>
}

switch

The switch statement allows you to easily check a certain variable and do an operation for different values. The same can be done with an if statement, however switch is generally cleaner for this purpose and can be more powerful.

An example switch statement:

my_var = 5;

switch(my_var) {
    case 1:
        /say it is 1;
    case 2:
        /say it is 2;
    case 3:
        /say less than or equal to 3;
        break;
    case 4:
        /say it is 4;
        break;
    case 5:
        /say it is 5;
        break;
    default:
        /say none of these;
        break;
}

Take special notice to the fact that there is no break at the end of both the 1 and 2 cases. break is used to 'exit' the switch statement and should normally be used before the next case starts. Without break, execution will 'fall through' and start executing the next case.

In this case, it allows us to display "it is 1" or "it is 2" as well as "less than or equal to 3".

Clone this wiki locally