A function body is a sequence of statements. So far all our statements were "void expressions" - an expression whose result is discarded.
This chapter shows all the other statements available. These statements change the flow of program execution: instead of sequentially executing statements they can selectively skip some statements or execute some statemets repeatedly.
The conditional statement is called if. The syntax is:
if cond then stmt
Multiline version (allows else):
if cond then stmt end if if cond then stmt1 else stmt2 end if
where cond is an expression that is evaluated. If the result is true, stmt1 is executed (else it is skipped). stmt1 is a single statement (or a block, see chapter 1). If an else is present,when cond is false, stmt2 is executed.
Syntax:
do while cond stmt loop
This will execute stmt repeatedly, 0 or more times, as long as cond is true. For example the following script will print 1, 2 and 3:
example program ch3_ex1 |
---|
n = 1 do while n < 4 fawk_print(n) n = n+1 loop |
It is a pre-test loop because cond is evaluated before executing stmt - this can result in zero executions of stmt if the condition is false before the first iteration.
When until is used instead of while, the condition is inverted: the loop continues until the condition becomes true (so the loop is executed as long as the condition is false).
Syntax:
do stmt loop while cond
This will execute stmt repeatedly, 1 or more times, as long as cond is true . For example the following script will print 1, 2 and 3:
example program ch3_ex2 |
---|
n = 1 do fawk_print(n) n = n + 1 loop while n < 4 |
It is a post-test loop because cond is evaluated after executing stmt - this means stmt is always executed at least once, even if the condition is false in the first iteration.
When until is used instead of while, the condition is inverted: the loop continues until the condition becomes true (so the loop is executed as long as the condition is false).
Syntax:
for var = expr1 to expr2 step expr3 stmt next var
The for loop runs var from value expr1 to expr2 in expr3 steps. The "step expr3" part is optional, when omitted +1 or -1 is used. next is always interpreted for the closest for, specifying var is optional.
The following example prints numbers 1, 2 and 3 (and is equivalent to the example in 3.3):
for n = 1 to 3 fawk_print(n) next n
The following example prints numbers 5, 10, 15 and 20:
for n = 5 to 20 step 5 fawk_print(n) next n
Note: the value of n after the loop is the last value it had in the loop - normally expr2, where the loop has terminated.