foreach item coll [function] [arguments] (tab) statement (tab) ... ...
Can be single line:
foreach(item coll [function] [arguments]) statement ...
item - variable that, on each loop, receives next item from coll collection. Type depends on other parts.
coll - typically, collection of some kind.
function - user-defined function that populates the item variable.
arguments - additional arguments for function.
statements - one or more statements (commands).
This statement is similar to rep and for. It simplifies enumeration of items in collections of various kinds. Block of statements is repeatedly executed for each item in collection.
Currently there are two predefined kinds of collections that may be used with foreach:
If function is not used, and coll is string, on each loop is extracted next line and stored into item variable. The variable must also be string (str or lpstr).
If function is not used, and coll is COM collection, on each loop is extracted next item and stored into item variable. Type of the variable must match type of collection elements, or can be VARIANT. The COM interface should be defined in a type library.
There is possibility to extend foreach. For example, use it to enumerate windows, files, etc. For this purpose is used user-defined function (function). The function is called at beginning of each loop. Typical purpose of this function - get next item from coll collection and assign it to item variable. Actually, coll can be anything (string, COM collection, array, variable of certain user-defined type, or not used at all). The function must have two or more arguments. First two arguments receive item and coll. They can have any type that is appropriate for function's purpose (however, first argument should be reference). Subsequent (optional) arguments can be used for additional arguments. The function must return one of the following int values: 1 - item is successfully extracted; 0 - no more items (break foreach loop). It also can return -1 to tell that last item is extracted. Despite the fact that the function is executed repeatedly, it retains the same local variables (including arguments) through whole foreach process. It allows, for example, to use local variable for internal indexing, or to know whether the function is being executed first time in current foreach. For examples, look for user-defined functions with FE_ prefix somewhere in System folder.
Use break to exit loop. Use continue to skip following statements.
foreach can be in other block (if, for, ...).
For each line: str s str lines="line1[]line2[][]line3" foreach s lines if(!s.len) continue out s For each COM object (enumerate environment variables): Wsh.WshShell shell._create VARIANT v foreach v shell.Environment out v