For (keyword)
This is a Language topic about Oxygene
Language Topics Introduction | Structured Overview | Grammar | Keywords | Functions
A for loop is a Oxygene statement, that is used to loop for a specified number of times, or over another structure.
'For' can work as a simple for, where an ordinal typed variable starts at a begin count, and goes up or down to another count.
It can also iterate over arrays and other structures that implement a generic or non-generic IEnumerable for each loop.
Simple For Loops
A simple 'for' loop uses the following syntax:
for i: Integer := 0 to 10 step 2 do
the i: Integer defines the name and data type of the identifier. The 'for' loop always introduces its own variable for the loop. The type can be implied, step is optional, and defaults to 1. To use a counter that counts down, the downto keyword has to be used instead of the to keyword.
For Each
'For each' can be used to iterate over anything that implements the IEnumerable interface. 'For each' uses this syntax:
for each el: String in mylist do for each matching el: String in mylist do for each el in mylist do for el in mylist do
In the first two cases the variable is typed, if it's not typed the type is inferred from the IEnumerable<T> (it will fail if it can't). The matching keyword will only execute the loop for values that really are of that type, so it will skip any non-strings. In the last case the 'each' keyword is left out, which is optional. The 'for each' is skipped completely if the value after in is nil.
Hidden catch when migrating from native Delphi
The scope of the iteration variable will always be limited to the loop itself.
If you already have an equally named variable outside the loop, Oxygene will emit a PW12 warning (name clash). But the outer variable will never get any value from inside the loop.
This might pose problems for code that comes from native Delphi, where you cannot declare loop variables directly at the beginning of the loop.
var x := -1; var list := new List<Integer>([1, 2, 3]); for x in list do Console.Writeline(x) Console.Writeline(x);Output:
1 2 3 -1
At the end, x will still be -1, because it is a different variable than the x inside the loop.
Shortcut syntax "for each"+"from"
Oxygene provides shortcut syntax for combining 'for each' and 'from' expressions.
Instead of
for each el in from v in myList do ...
you can write the same in a more natural way:
for each from el in myList do ...
Step
In loops it can be useful to restrict processing to a subset by examining only every n'th item. The step value is variable, however it's only evaluated once. Changing the step value from within the loop won't affect the action step value.
for i: Int32 := 1 to 365 step 7 do ..
Parallel Loops
It's possible to process the body of the loop in parallel through the parallel framework. See Parallel Loops for more information.