Scoping

Handling the visibility of variables.

In RapidScript, a scope is a region of the program where certain declared variables are accessible to the user. Scopes can be nested and contain other scopes within them. A variable declared within a scope is only visible within the same scope or any nested sub-scopes. The variable is not visible to any containing scopes.

Every RapidScript program by default has a global scope in which all global variables and functions are declared. In the global scope, only function definitions and variable declarations / definitions are allowed. Variables declared in this scope can be seen everywhere throughout the program. All subsequent scopes are nested within the global scope.

Scopes are created within the { and } characters (except for the global scope, which exists automatically).

Function bodies and multi-line bodies of conditional statements require a { } pair to define a new scope. In function bodies, the function's parameter are accessible as variables in the scope.

For example:

int32 globalInt = 0;

// This is the global scope. Only globalInt is accessible here.
// We can only define functions and variables here.

void function(int32 parameterInt)
{
    int32 functionInt = 2;
    
    // This is the function's scope.
    // Visible variables:
    //    globalInt
    //    parameterInt
    //    functionInt
    
    if (parameterInt == 1)
    {
        int32 conditionalInt = 3;
        
        // This is the conditional statement's scope.
        // Visible variables:
        //    globalInt
        //    parameterInt
        //    functionInt
        //    conditionalInt
        
        {
            int32 localInt = 4;
            
            // This is a local scope created by the {} characters.
            // Visible variables:
            //    globalInt
            //    parameterInt
            //    functionInt
            //    conditionalInt
            //    localInt
        }
        
        // Back to the conditional statement's scope
    }
    
    // Back to the function's scope
}

// Back to the global scope

Last updated