System information

Manual:Scripting
25
Scopes
Variables can be used only in certain regions of the script. These regions are called scopes. Scope determines
visibility of the variable. There are two types of scopes - global and local. A variable declared within a block is
accessible only within that block and blocks enclosed by it, and only after the point of declaration.
Global scope
Global scope or root scope is default scope of the script. It is created automatically and can not be turned off.
Local scope
User can define its own groups to block access to certain variables, these scopes are called local scopes. Each local
scope is enclosed in curly braces ("{ }").
{
:local a 3;
{
:local b 4;
:put ($a+$b);
}
#line below will generate error
:put ($a+$b);
}
In code above variable b has local scope and will not be accessible after closed curly brace.
Note: Each line written in terminal is treated as local scope
So for example, defined local variable will not be visible in next command line and will generate
syntax error
[admin@MikroTik] > :local myVar a;
[admin@MikroTik] > :put $myVar
syntax error (line 1 column 7)
Warning: Do not define global variables inside local scopes.
Note that even variable can be defined as global, it will be available only from its scope unless it is
not already defined.
{
:local a 3;
{
:global b 4;
}
:put ($a+$b);
}
Code above will generate an error.