Repeat for each item in collection

Syntax

foreach item coll [function] [arguments]
(tab)statements
(tab)...

 

Can be single line:

foreach(item coll [function] [arguments]) statements

 

Parameters

item - variable that in each loop receives next item from coll collection. Type depends on other parameters.

coll - usually a collection of some kind.

function - a user-defined function that populates the item variable.

arguments - additional arguments for function.

 

Remarks

foreach is similar to rep and for. It simplifies enumeration of items in collections of various kinds. Executes statements for each item in the collection.

 

Currently there are two predefined kinds of collections that may be used with foreach. Used without function.

 

1. For each line in string.

If coll is string, in each loop is extracted next line and stored into item variable. The variable must also be string (str or lpstr).

 

2. For each item in COM collection.

If coll is a COM collection interface, in 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, enumerate windows, files, etc. Read more.

For this purpose is used a user-defined function (function). foreach executes the function at the beginning of each loop. The function gets next item from coll collection and assign it to item variable. Actually coll can be anything (string, array, variable of a user-defined type, or not used at all).

 

The function must have two or more parameters. The first two parameters receive item and coll. They can have any type that is appropriate for function's purpose, but the first parameter should be reference. Other optional parameters will receive arguments.

 

The function must return: 1 - an item extracted; 0 - no more items (break foreach loop). It also can return -1 to tell that last item is extracted.

 

Although the function is executed repeatedly, it retains the same local variables (including parameters) through whole foreach. For example, you can use a local variable for internal indexing or one-time initialization.

 

Example function FE_Char:

 /
function int&character $s

 Gets characters from string.

int i
if(s=0 or s[i]=0) ret
character=s[i]
i+1
ret 1

 

Using it:

int c
foreach c "ABC" FE_Char
	out c

 

 

Use break to exit loop. Use continue to skip following statements.

 

foreach can be in other block (if, for, ...).

 

Examples

 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