System information
Manual:Scripting
34
:global myFunc do={ :return ($a + $b)}
:put [$myFunc a=6 b=2]
output:
8
You can even clone existing script from script environment and use it as function.
#add script
/system script add name=myScript source=":put \"Hello $myVar !\""
:global myFunc [:parse [/system script get myScript source]]
$myFunc myVar=world
output:
Hello world !
Warning: If function contains defined global variable which name matches the name of passed parameter,
then globally defined variable is ignored, for compatibility with scripts written for older versions. This feature
can change in future versions. Avoid using parameters with same name as global variables.
For example:
:global my2 "123"
:global myFunc do={ :global my2; :put $my2; :set my2 "lala"; :put $my2 }
$myFunc my2=1234
:put "global value $my2"
Output will be:
1234
lala
global value 123
Catch run-time errors
Starting from v6.2 scripting has ability to catch run-time errors.
For example, [code]:reslove[/code] command if failed will throw an error and break the script.
[admin@MikroTik] > { :put [:resolve www.example.com]; :put "lala";}
failure: dns name does not exist
Now we want to catch this error and proceed with our script:
:do {
:put [:resolve www.example.com];
} on-error={ :put "resolver failed"};
:put "lala"
output: