Walk loops
walk runs a block once for each element of a list, set or map. For a loop with a condition, see while.
nums: [int] = [10, 20, 30]
nums.walk(n) {
print(n)
}Output:
10
20
30n is a new variable. It holds the current element and exists only inside the block. Its type is the element type, so here it is an int.
The block starts on the same line as walk(...), just like the block of an if.
Lists, sets and maps
Walking a list gives its elements from first to last. Walking a set gives its elements in the order they were added:
ids: {int} = {5, 12, 3}
ids.walk(id) {
print(id)
}Output:
5
12
3With two variables, walking a list also gives each element’s position, counted from 0: the position first, then the element. One variable is enough when the positions aren’t needed.
a: [int] = [3, 4, 5, 6, 7, 8, 9]
a.walk(i, n) {
if i == 3 {
stop
}
print("${i}: ${n}")
}Output:
0: 3
1: 4
2: 5The position is a copy: changing it in the block doesn’t change where the walk goes. To walk only some of a list, walk a part of it: a.part(0, 5).walk(n) { ... }.
Walking a map gives two variables: the key, then its value. The keys come in the order they were added:
ages: {str: int} = {"Alice": 30, "Bob": 17}
ages.walk(name, age) {
print("${name} is ${age}")
}Output:
Alice is 30
Bob is 17Anything that gives a list, set or map can be walked, for example a literal or an element of a map:
groups: {str: [str]} = {"admins": ["ann", "bo"]}
groups["admins"].walk(user) {
print(user)
}
[1, 2].walk(x) {
print(x * 10)
}Output:
ann
bo
10
20skip: go on with the next element
skip ends the current step. The walk goes on with the next element:
nums: [int] = [1, -2, 3, -4, 5]
nums.walk(n) {
if n < 0 { skip }
print(n)
}Output:
1
3
5stop: end the walk
stop ends the whole walk. The program goes on after its block:
nums: [int] = [1, 2, 3, 100, 5, 6]
nums.walk(n) {
if n > 50 { stop }
print(n)
}
print("done")Output:
1
2
3
doneskip and stop are bare words, without parentheses. Each one does exactly one thing, and they can be combined:
nums: [int] = [1, -2, 3, -4, 5, 100, 6]
nums.walk(n) {
if n < 0 { skip }
if n > 50 { stop }
print(n)
}Output:
1
3
5Common patterns
Find the first match:
names: [str] = ["Alice", "Bob", "Charlie"]
found: str = ""
names.walk(name) {
if name == "Bob" {
found = name
stop
}
}
print(found)Output:
BobAdd things up:
prices: {str: float} = {"tea": 2.5, "cake": 4.0}
total: float = 0.0
prices.walk(item, price) {
total = total + price
}
print(total)Output:
6.5Walks inside walks:
grid: [[int]] = [[1, 2], [3, 4]]
grid.walk(row) {
row.walk(x) {
print(x)
}
}Output:
1
2
3
4Ranges: counting
(a..b).walk(i) counts from a to b, b included. To count down, add .down():
(1..3).walk(i) {
print(i)
}
(3..1).down().walk(i) {
print("${i}...")
}
print("go!")Output:
1
2
3
3...
2...
1...
go!A range counts in one direction only, so its meaning never depends on the numbers. Going up, an end below the start walks nothing; going down, an end above it walks nothing. So “n times” walks nothing when n is 0:
n: int = 0
(1..n).walk(k) {
print("never")
}
(5..0).walk(k) {
print("never: going up, 5..0 is empty")
}
print("done")Output:
doneSteps
.step(n) counts n at a time. The walk ends at the last number that isn’t past the end, so the end is only reached when the counting lands on it:
(0..100).step(25).walk(i) {
print(i)
}
(0..10).step(4).walk(i) {
print("by 4: ${i}")
}
(10..0).down().step(5).walk(i) {
print("down: ${i}")
}Output:
0
25
50
75
100
by 4: 0
by 4: 4
by 4: 8
down: 10
down: 5
down: 0The step is how much to count by, at least 1: the direction is
.down()’s job..step(0)and.step(-2)are compile errors; a step worked out when running that is below 1 raises error 1 (a range's step must be at least 1, not -2)..down().step(5)and.step(5).down()mean the same.The count never goes past the end, so a range can end at the largest or smallest int without wrapping around.
The bounds and the step are ints, worked out once before the walk starts.
The count is a copy: changing it in the block doesn’t change the walk.
skipandstopwork as in any walk.A range is only walked: it has no other use, and is written in its own parentheses (
(0..5).walk(i), not0..5).For a list’s positions, walk the list:
a.walk(i, x)gives each position and element.
Changing what you walk
A walk goes over the elements the list, set or map had when the walk started. You can change it inside the block: the changes happen, but they don’t affect the walk. Added elements aren’t visited, removed ones still are, and replaced values show up only after the walk.
nums: [int] = [1, 2, 3]
nums.walk(n) {
nums[] = n * 10
}
print(nums)Output:
[1, 2, 3, 10, 20, 30]So it’s safe to remove elements while walking, for example to drop all minors from a map:
ages: {str: int} = {"Alice": 30, "Bob": 17, "Cid": 12}
ages.walk(name, age) {
if age < 18 {
remove(ages, name)
}
}
print(ages)Output:
{"Alice": 30}(Luma does this by walking over a copy, which is made when the walk starts. The copy is shallow: a list inside a list is the same list, not a copy of it.)
skip, stop and try
skip and stop belong to the innermost loop, a walk or a while. Inside a walk inside a walk, they end the step or the walk of the inner one only.
A skip or stop inside a try leaves the try too. The error variable keeps the value it had before.
An error raised inside a walk ends the walk and goes to the nearest try, like everywhere else:
err: error = nil
try err {
[1, 2, 3].walk(n) {
if n == 2 {
throw error(100, "found 2")
}
print(n)
}
}
print(err.message)Output:
1
found 2Rules
- A list walk takes one variable (the element) or two (its position, then the element); a set walk one; a map walk two, the key and the value.
- The variables follow the usual rules: their names can’t be in use already, and they exist only inside the block.
skipandstopcan only be used inside a walk or a while:
skip // error: skip can only be used inside a walk or a while
x.walk(n) -> { } // error: walk needs no ->
m.walk(k) { } // error: walking a map gives a key and a value, so it needs two variablesNot available yet
- Ranges with steps, like every second number (count with a while for now).
- Leaving an outer walk from an inner one (labeled loops).
See Limitations.