for Loop
The for loop iterates over a numeric range. It supports ascending (to) and descending (downto) sequences with an optional step value.
Ascending
for i in 0 to 5 do # 0, 1, 2, 3, 4
# body
end
for i in 0 to 10 by 2 do # 0, 2, 4, 6, 8
# body
end
Descending
for i in 5 downto 0 do # 5, 4, 3, 2, 1
# body
end
for i in 10 downto 0 by 2 do # 10, 8, 6, 4, 2
# body
end
Exclusive Bounds
Bounds are always exclusive - the end value is never reached. For to, the bound behaves like <. For downto, it behaves like >.
To iterate over an inclusive range, adjust the bound by one:
for i in 1 to 10 + 1 do # 1 through 10 inclusive
# body
end
for i in 10 downto 1 - 1 do # 10 through 1 inclusive
# body
end
Evaluation
The start, end, and step expressions are evaluated once at loop entry. Modifying variables used in these expressions during the loop body has no effect on the iteration range.
Loop Variable Scoping
The loop variable is scoped to the loop body. It is not accessible before or after the loop.
for i in 0 to 5 do
# i is available here
end
# i is NOT available here