Nesting :if and :foreach in scripts

G’day,

I have a situation where I need to run a section of a script to clear out previously configured information on a MikroTik router based on whether a variable is set. Some of the stuff needing clearing is done with a :foreach loop as there may well be multiple instances to wipe out, however it seems that once I enclose this inside a :if loop, the :foreach then becomes invalid and fails to run.

When I run the below code, it executes perfectly:

/interface pppoe-client remove [find]
:foreach item in=[/interface wireless find interface-type="virtual"] do={remove $item}

However, when I try this, the :foreach bombs out:

if ($nukePave = "Yes") do={
  /interface pppoe-client remove [find]
  :foreach item in=[/interface wireless find interface-type="virtual"] do={remove $item}
}

Does anyone have thoughts on a) whether this is a MikroTik scripting bug/shortcoming, or b) if there’s a better way to achieve what I’m after without needing nesting that’s not working.

Have a look in the Wiki:
http://wiki.mikrotik.com/wiki/Manual:Scripting#Loops_and_conditional_statements

You have to use for and not foreach.

I’ve read that Wiki page quite a bit and still can’t see where it says anything about which types of loops can be nested and in which other types of loops they can be nested.

The problem with “for” as compared to “foreach” is that it is a very, very different type of loop. I suppose I could first do a “foreach” and drop the results into an array that the “for” then handles. It’s a more complicated way to handle it, so I wonder if the MikroTik team will look at this for the (hopefully not vaporware) RouterOS Version 7 upcoming release - allowing nesting of all loop types will allow for much more powerful scripting with less code needed. :slight_smile: