Iterators and the for statement
The for statement is an abstract mechanism to iterate over the elements of a container. It relies on an iterator to do so. Like while statements, for statements open an implicit block so that they can be left with a break statement.
The for loop declares iteration variables - their scope reaches until the end of the loop body. The iteration variables’ types are inferred by the return type of the iterator.
An iterator is similar to a procedure, except that it can be called in the context of a for loop. Iterators provide a way to specify the iteration over an abstract type. The yield statement in the called iterator plays a key role in the execution of a for loop. Whenever a yield statement is reached, the data is bound to the for loop variables and control continues in the body of the for loop. The iterator’s local variables and execution state are automatically saved between calls. Example:
# this definition exists in the system module
iterator items*(a: string): char {.inline.} =
var i = 0
while i < len(a):
yield a[i]
inc(i)
for ch in items("hello world"): # `ch` is an iteration variable
echo ch
The compiler generates code as if the programmer had written this:
var i = 0
while i < len(a):
var ch = a[i]
echo ch
inc(i)
If the iterator yields a tuple, there can be as many iteration variables as there are components in the tuple. The i’th iteration variable’s type is the type of the i’th component. In other words, implicit tuple unpacking in a for loop context is supported.