-
Notifications
You must be signed in to change notification settings - Fork 2
Loops
There are 4 basic and 1 special types of loops in TaffyScript.
Note: on all of the examples, I put the loop body in curly braces. If you have a simple (one-line) statement, you don't have to do that. For more complex bodies, it is still necessary.
A repeat loop has the following form:
repeat(number) {
//body goes here
}
number
can be a constant or an expression that results in a number. The code in the repeat body will execute the specified number of times.
A while loop has the following form:
while(condition) {
//body goes here.
}
The code in the while body will continue to execute while the condition is true or a break statement is hit.
A do-until loop has the following form
do {
//body goes here
}
until(condition)
The code in the do body will continue to execute until the until condition is true. Unlike a while loop, the do-until loop will always execute at least once.
A for loop has the following form:
for(init ; condition ; increment) {
//body goes here
}
This loop is obviously a bit more complicated. First, the init
segment is executed. Then, while the condition is true, the body executed. After each execution of the body, the increment code is run. A better example:
for(var i = 0; i < 10; i++) {
print(i);
}
The init
segment is optional, but the condition
and increment
parts are mandatory.
If the code hits a continue statement in any loop, it stop executing the current iteration of the body and move directly on to the next. For example, the following code uses continue to only output even numbers:
for(var i = 0; i < 10; i++) {
if(i % 2 == 1) {
continue;
}
print(i);
}
If the code hits a break statement in any loop, it will stop all execution of the current loop.