Set global variable

It seems the system doesn’t like my script

:global activeCh first
:global auxCh second

:global setActiveCh do={
  :if ($activeCh = $"ch") do={
    :log info "Keep $activeCh"
  } else={
    :log info "Switch $activeCh to $ch"

    :set auxCh $activeCh
    :set activeCh $ch
  }
}

I have found that the problem is in the “:set” lines, but I just can’t get what is wrong, can someone help ?
Is there a way to localize script errors except extrasensory perception ?

It’s meaningless,
like the phrase you wrote “extrasensory perception”

Do two lines of code thrown out at random without description seem normal to you?

There are three globals in the script, and two set commands - quite obvious.
If script runned as it is, nothing happens, and no global gets defined
But if you remove set commands, it works as expected.
So I suppose something wrong with these set-s
Rephrasing initial question: "Do you see any issues with set commands ?"

no, the problem is elsewhere.

:global activeCh "first"
:global auxCh    "second"

:global setActiveCh do={
    :global activeCh
    :global auxCh
    :if ($activeCh = $ch) do={
        :log info "Keep $activeCh"
    } else={
        :log info "Switch $activeCh to $ch"
        :set auxCh    $activeCh
        :set activeCh $ch
    }
}


:put $activeCh
:put $auxCh
$setActiveCh ch="third"
:put $activeCh
:put $auxCh

The issue is global variables need to be “declared” in the function before use. Even if they are assigned in the same script. Once declared, like in the following, it should work:

:global activeCh first
:global auxCh second

:global setActiveCh do={
   :global activeCh
   :global auxCh
  :if ($activeCh = $"ch") do={
    :log info "Keep $activeCh"
  } else={
    :log info "Switch $activeCh to $ch"

    :set auxCh $activeCh
    :set activeCh $ch
  }
}

The docs speak of “scope”: https://help.mikrotik.com/docs/display/ROS/Scripting – and the function block is same as local scope, thus different from “global” scope.

Now what’s mildly annoying, and your need for “ESP”, is there is no error by using or even attempting to set an un-declared variable in local scope – as you see from your original code: it sets nothing, but doesn’t produce an error even though it’s not defined.

Basically you need add “:global ” for ANY variable/function defined outside the scope, you are going to use inside the current “scope” (e.g. do={} block here).

Thanks a lot ! Works fine :ok_hand:

BTW, I knew I read this at some point… The old wiki actually describe this in a “Tips and Tricks” – other useful gems likely in here that AFAIK aren’t in the newer help.mikrotik.com docs:

https://wiki.mikrotik.com/wiki/Manual:Scripting_Tips_and_Tricks#Accessing_global_variable_from_function

I suppose they are developing people’s ESP this way)
or I can’t imagine another reason why doesn’t they put some log message at least