Imagine that we want our script to print out a message five times. We could write:-
printline "Hello from mash"
printline "Hello from mash"
printline "Hello from mash"
printline "Hello from mash"
printline "Hello from mash"
This is perfectly valid but a touch verbose. Using a simple loop we can reduce the lines of code that we have to write. (Programmers are always looking for ways to do that.) Here is that same mashlet re-written to use an each loop and a range instead.
Each loops
Natural
each 1...5
printline "Hello from mash"
end
Standard
each (1...5) {
printline("Hello from mash")
}
Output
Hello from mash
Hello from mash
Hello from mash
Hello from mash
Hello from mash
We can use loops to walk through arrays and dictionaries of data and act upon each item in turn. We need to tell MaSH how to represent the current value using an as statement and a new variable name. MaSH will then pass this to the code inside the loop as a variable.
Natural
set fruits to ["apples", "bananas", "cherries"]
# Using an as statement we create a variable called fruit which MaSH passes to the code inside the loop
each fruits as fruit
printline "I would like some {{ fruit }}"
end
Standard
fruits = ["apples", "bananas", "cherries"]
# Using an as statement we create a variable called fruit which MaSH passes to the code inside the loop
each (fruits as fruit) {
printline("I would like some {{ fruit }}")
}
Output
I would like some apples
I would like some bananas
I would like some cherries
While and Until loops
A while loop has much in common with an if statement. On each loop it evaluates a condition to determine whether to execute the code inside the loop. If our condition is false to begin with then the code inside the loop will never be executed.
Natural
set x to 0
while x is less than 5
printline x
set x to x + 1
end
Standard
x = 0
while (x < 5) {
printline(x)
x = x + 1
}
Output
0
1
2
3
4
An until loop works in the opposite way to a while loop. Instead of executing the code that it contains whilst a condition is true, it executes until the condition is true. If the condition is true to begin with then the loop will be skipped entirely.
Natural
set x to 0
until x is greater than 4
printline x
set x to x + 1
end
Standard
x = 0
until (x > 4) {
printline(x)
x = x + 1
}
Output
0
1
2
3
4