V4.0 RC1 - script bug - variable scope/lifetime :foreach

index variable used in :foreach sentence will live only inside :foreach scope.
If variable used is local or global it will be destroyed.

# Define Local Variables
:local rt

# Loop thru interfaces and look for ones containing
# default gateways without routing-marks
:foreach rt in=[/ip route find dst-address=0.0.0.0/0 active=yes] do={:log info [/ip route get $rt gateway-status]}
:log info [/ip route get $rt gateway-status]

:log info sentence WORKS only inside :foreach
outside :foreach will break script execution!

following code with one more variable, will workaround the problem:

# Define Local Variables
:local rt

# Loop thru interfaces and look for ones containing
# default gateways without routing-marks
:foreach frt in=[/ip route find dst-address=0.0.0.0/0 active=yes] do={:set rt $frt}
:log info [/ip route get $rt gateway-status]

I don’t think that’s a bug, that’s just the scope rules of the language. Some languages create a new scope for foreach loops (like Perl) so that variables in a greater surrounding scope with the same variable name do not leak inside:

sh-3.2$ perl -e 'my @a=("a","b","c"); my $a; foreach $a(@a) { print $a . " ";} print "\nAfter: $a\n";'
a b c 
After:

And the same workaround:

sh-3.2$ perl -e 'my @a=("a","b","c"); my $b; foreach $a(@a) { print $a . " "; $b = $a;} print "\nAfter: $b\n";'
a b c 
After: c

Others, like Ruby, don’t:

sh-3.2$ ruby
x = String.new
['a','b','c'].each{|x| print "#{x} "}
puts "\nAfter: #{x}"     
a b c 
After: c

More importantly, this scope handling hasn’t changed in 4rc1, here’s the same test on 3.30:

[admin@MikroTik] > /system package pri
Flags: X - disabled 
 #   NAME                    VERSION                    SCHEDULED              
 0   system                  3.30                                              
 1   advanced-tools          3.30                                              
 2   routerboard             3.30                                              
 3   ipv6                    3.30                                              
 4   dhcp                    3.30                                              
 5   security                3.30                                              
 6   hotspot                 3.30                                              
[admin@MikroTik] > :local rt; :foreach rt in=[/ip route find dst-address=0.0.0.0/0 active=yes] do={:put "inside loop: $rt"}; :put "outside loop: $rt";
inside loop: *1
outside loop:

yeah, it’s dangerous to use for loop variable outside a loop itself. behaviour of this is not defined in many programming languages

As it was already mentioned, this is not a bug. Please read the manual
http://wiki.mikrotik.com/wiki/Scripting#Scopes