Conditionals and loops
Conditional statements
A conditional statement lets your program choose different paths depending on some (boolean) condition.
A conditional statement consists of an if block followed by zero to many else if blocks and, optionally, one else block. Each block, except the else block, has some guard condition which must be of type boolean. When executing a conditional statement, FlowScript finds the first block whose guard condition is true and executes the statements in that block. It then leaves the conditional statement. If none of the guarded blocks are executed, but an else block exists, then the else block is executed.
In other words, at most one of the blocks of a conditional statement will be executed.
Blocks which contain only one statement may be written with a single colon instead of a pair of curly braces:
Loops
Loops let you repeat blocks of code for each element of a sequence, or until some condition is met.
for loops
To repeat a block of code for each element in a sequence, use a for loop. A for loop consists of an iterator name, a sequence expression and a loop body.
In the example above, n is the iterator name and numbers is the sequence expression. In plain language, the loop might be understood to say: "for each element in the variable numbers, assign that element to a local variable called n, and then run the statement inside the loop body with n added to the scope".
while loops
To repeat a block of code until some boolean condition is no longer true, use a while loop. A while loop consists of a condition expression and a body. The execution of the body is repeated until the condition is no longer true. If the condition is false in the first place, the loop body is never executed.
While loops should be used cautiously. Since the body of a while loop is repeated until the condition expression is false, it follows that each repetition of the body must somehow bring the condition closer to being false. In the example above, each iteration decrements the value of n by one, making sure that the expression n > 0 will eventually be false.
Failure to construct a while loop in such a way that the condition will eventually be false is called an infinite loop. It will stop your application in its tracks.
break
The break statement can be used in both for loops and while loops. It causes the program to immediately stop the current iteration of the loop and perform no more iterations.
continue
The continue statement can be used in both for loops and while loops. It causes the program to stop the current iteration of the loop and proceed with the next.
Last updated