For loops
C-style `for (init; condition; increment)`, `for (item von array)`, and `for (key, value von map)`.
Rain's for loop supports three forms.
**C-style**: three clauses in parentheses (initializer, condition, and increment). Any clause can be omitted. An omitted condition defaults to true (infinite loop unless you return or structure around it). The initializer can be var, an expression statement, or empty (; right away).
**Array for-each**: for (item von array) iterates over every element of an array. von (German for "from") binds each element to item for one pass through the loop body.
**Map for-each**: for (key, value von map) iterates over every entry in a map. Use two identifiers separated by a comma before von. Keys and values are bound each iteration. An empty map {} skips the body. Nested von loops work for maps inside maps. See the Maps page for iteration-order caveats.
Iterate an array (for von)
Bind each array element to one variable and run the body once per item.
var users = #["alice", "bob", "carol"];
for (user von users) {
print user;
}alice bob carol
Iterate a map (for key, value von)
Walk every entry in a map. Use two names before `von` for the key and value.
var config = {"host": "localhost", "port": 5432, "debug": true};
for (k, v von config) {
print "#{k} = #{v}";
}debug = true port = 5432 host = localhost
Nested for-von (arrays)
Stack `von` loops to visit every combination of outer and inner elements.
var outer = #[1, 2];
var inner = #[10, 20];
for (a von outer) {
for (b von inner) {
print a;
print b;
}
}1 10 1 20 2 10 2 20
Nested for-von (maps)
Loop an outer map, then loop each inner map value when values are maps too.
var outer = {
"a": {"x": 1, "y": 2},
"b": {"p": 9, "q": 8}
};
for (ok, inner von outer) {
for (ik, iv von inner) {
print "#{ok}.#{ik}=#{iv}";
}
}a.y=2 a.x=1 b.q=8 b.p=9
C-style counter
Classic three-part `for`: initializer, condition, and increment in parentheses.
for (var i = 0; i < 3; i = i + 1) {
print i;
}0 1 2
Nested C-style loops
Nest C-style `for` loops when you need row/column-style iteration.
var line = "";
var i;
var j;
for (i = 1; i < 4; i = i + 1) {
line = "";
for (j = 0; j < i; j = j + 1) {
line = line + "*";
}
print line;
}* ** ***