rhai/doc/src/language/for.md

70 lines
1.6 KiB
Markdown
Raw Normal View History

2020-06-20 06:06:17 +02:00
`for` Loop
==========
{{#include ../links.md}}
2020-07-26 04:05:47 +02:00
Iterating through a range or an [array], or any type with a registered _iterator_,
is provided by the `for` ... `in` loop.
2020-06-20 06:06:17 +02:00
2020-06-21 18:03:45 +02:00
Like C, `continue` can be used to skip to the next iteration, by-passing all following statements;
`break` can be used to break out of the loop unconditionally.
2020-06-20 06:06:17 +02:00
```rust
// Iterate through string, yielding characters
let s = "hello, world!";
for ch in s {
2020-06-21 18:03:45 +02:00
if ch > 'z' { continue; } // skip to the next iteration
2020-06-25 05:07:56 +02:00
2020-06-20 06:06:17 +02:00
print(ch);
2020-06-25 05:07:56 +02:00
2020-06-21 18:03:45 +02:00
if x == '@' { break; } // break out of for loop
2020-06-20 06:06:17 +02:00
}
// Iterate through array
let array = [1, 3, 5, 7, 9, 42];
for x in array {
2020-06-21 18:03:45 +02:00
if x > 10 { continue; } // skip to the next iteration
2020-06-25 05:07:56 +02:00
2020-06-20 06:06:17 +02:00
print(x);
2020-06-25 05:07:56 +02:00
2020-06-21 18:03:45 +02:00
if x == 42 { break; } // break out of for loop
2020-06-20 06:06:17 +02:00
}
// The 'range' function allows iterating from first to last-1
for x in range(0, 50) {
2020-06-21 18:03:45 +02:00
if x > 10 { continue; } // skip to the next iteration
2020-06-25 05:07:56 +02:00
2020-06-20 06:06:17 +02:00
print(x);
2020-06-25 05:07:56 +02:00
2020-06-21 18:03:45 +02:00
if x == 42 { break; } // break out of for loop
2020-06-20 06:06:17 +02:00
}
// The 'range' function also takes a step
2020-06-21 18:03:45 +02:00
for x in range(0, 50, 3) { // step by 3
if x > 10 { continue; } // skip to the next iteration
2020-06-25 05:07:56 +02:00
2020-06-20 06:06:17 +02:00
print(x);
2020-06-25 05:07:56 +02:00
2020-06-21 18:03:45 +02:00
if x == 42 { break; } // break out of for loop
2020-06-20 06:06:17 +02:00
}
// Iterate through object map
let map = #{a:1, b:3, c:5, d:7, e:9};
2020-06-21 18:03:45 +02:00
// Property names are returned in unsorted, random order
2020-06-20 06:06:17 +02:00
for x in keys(map) {
2020-06-21 18:03:45 +02:00
if x > 10 { continue; } // skip to the next iteration
2020-06-25 05:07:56 +02:00
2020-06-20 06:06:17 +02:00
print(x);
2020-06-25 05:07:56 +02:00
2020-06-21 18:03:45 +02:00
if x == 42 { break; } // break out of for loop
2020-06-20 06:06:17 +02:00
}
2020-06-21 18:03:45 +02:00
// Property values are returned in unsorted, random order
2020-06-20 06:06:17 +02:00
for val in values(map) {
print(val);
}
```