Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
actor Main
new create(env: Env) =>
let names = ["Alice"; "Bob"; "Carol"]
let scores = [as U32: 95; 87; 91]
try
let iter1 = names.values()
let iter2 = scores.values()
while iter1.has_next() and iter2.has_next() do
(let name, let score) = (iter1.next()?, iter2.next()?)
env.out.print(name + ": " + score.string())
end
end
7 changes: 7 additions & 0 deletions code-samples/control-structures-loops-for-multi.pony
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
actor Main
new create(env: Env) =>
let names = ["Alice"; "Bob"; "Carol"]
let scores = [as U32: 95; 87; 91]
for (name, score) in (names.values(), scores.values()) do
env.out.print(name + ": " + score.string())
end
18 changes: 18 additions & 0 deletions docs/expressions/control-structures.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,24 @@ Note that the variable __name__ is declared _let_, so you cannot assign to the c

__Can I use break and continue with for loops?__ Yes, `for` loops can have `else` expressions attached and can use `break` and `continue` just as for `while`.

#### Multiple iterators

A `for` loop can iterate over multiple collections at once. Place a tuple of iterators after `in` and a matching tuple of names after `for`:

```pony
--8<-- "control-structures-loops-for-multi.pony:3:7"
```

The names after `for` are bound to the values from each iterator in order. The loop stops when any iterator is exhausted, so the shortest one determines the number of iterations.

You can think of the multi-iterator form as equivalent to one iterator variable per position and an AND-chained condition:

```pony
--8<-- "control-structures-loops-for-multi-while-comparison.pony:6:11"
```

`break`, `continue`, and `else` work the same as with a single iterator.

### Repeat

The final loop construct that Pony provides is `repeat` `until`. Here we evaluate the expression in the loop and then evaluate a condition expression to see if we're done or we should go round again.
Expand Down
Loading