Skip to content
Tom Barham edited this page Sep 14, 2015 · 3 revisions

Blocks are scoped sections of code in MCA, to which you can pass arguments. Typically, blocks are used when defining a macro with arguments, however they can also be used to take advantage of the return statement or the scoping properties (for more information on the recommended coding style, see Style Guide).

Note: statements like if, while, and switch are not blocks, and follow different rules to blocks. For more information, see Block Statements

To define a simple block without any arguments, use a set of empty brackets and braces. This block can be placed into a variable, or called instantly:

// the last () executes the block immediately
() {
    /say Hello!;
}();

// equivalent to:

say_hello = () {
    /say Hello!;
};
say_hello();

Arguments

To define a block with arguments, pass a comma-delimited list of argument names in the brackets:

(message) {
    /say {message}!;
}("Hello");

// equivalent to:

say_something = (message) {
    /say {message}!;
};
say_something("Hello");

Return values

We can return values from the block, with the return keyword:

add_one = (number) {
    return number + 1;
};
/say 1 + 1 = {add_one(1)};

The return keyword immediately exits the block and returns to the call position.

out arguments

out arguments allow for multiple outputs from a block, by reversing the bind direction. Note: both parties (the caller and block definition) must consent for an argument to be an out argument, or otherwise a syntax error will be fired.

Example:

add_one = (number, out result) {
    result = number + 1;
};

add_one(1, out new_number);
/say 1 + 1 = {new_number};

Note: out parameters should only be used if multiple return values must be provided. Otherwise, use return values.

Overloads

MCA supports 'overloaded' macros. These are block macros with the same name, but a different set of arguments, and can be used to provide default argument values, or slightly different handling for different arguments.

To create an overloaded macro, simply provide the macro multiple times:

MY_MACRO(one) {
   /say one argument!;
}
MY_MACRO(one, two) {
    /say two arguments!;
}
MY_MACRO(one, two, three) {
    /say three arguments!;
}

MY_MACRO(1, 2);
MY_MACRO(5, 3, 10);

// becomes:
/say two arguments!;
/say three arguments!;

Scope access

All blocks have a global scope access - this means that they can only access global variables. They cannot access variables in the parent block, if one exists. As a result, the following code will not work, because my_value is not defined inside the block:

() {
    my_value = 1;
    add_one = () {
        my_value++;
    };
    
    add_one();
}();

Clone this wiki locally