suve

awful: tutorial: conditional statements

So far we have only written scripts which always ran in the exact, same, linear way. Wouldn't it be fun being able to write a script which can act differently, depending on e.g. input data? Sure it would! So, let's take a look at how to do it, shall we?

I have this one condition...

:set &num i0
:writeln s'Input one number: '
:read &num
!if $num
    :writeln s'Number is non-zero, yay!'
!fi
:writeln s;Your numer was: ; $num

The above example demonstrates how a conditional statement is made in awful. It also introduces us to a new element in the syntax: language constructs - here, the !if and !fi constructs were used. As one can guess, language constructs in awful are prefixed by the exclamation mark (!) character. Language constructs differ from functions in that they have a special meaning - like here, defining a conditional statement - and cannot be used as sub-expressions. When an language construct is put inside another expression, the interpreter treats this as if a newline was put before the construct.

The !if construct is used to make a conditional statement. It takes any number of arguments and performs a logical AND on them - though usually, we will only pass a single argument. As can be seen in the example above, arguments can be a variables - they will be silently cast to boolean. If the condition evaluates to TRUE, the interpreter will execute the expressions put into conditional body. The end of conditional expressions is marked by the !fi construct.

Fulfil my will, or face my wrath

Quite often in programming, aside from doing something if a condition is true, we also want to perform some different actions if the check proves otherwise. Obviously, awful couldn't be missing on such an important feature.

:set &num i0
:writeln s'Input one number: '
:read &num
!if $num
    :writeln s'Number is non-zero, yay!'
!else
    :writeln s'Did you really have to choose zero?'    
!fi

As can be seen from the example above, this can be achieved by using the !else construct, which separates the true and false parts of expression list. If the condition evaluates to true, only expressions between the !if and !else constructs will be executed - and if it's false, the interpreter will execute statements appearing between !else and !fi.

It should be noted that !else should appear alone on the line, not followed by any expression.


Next: ⇒ Comparisons and boolean logic ⇒
Back: ⇐ Chaining expressions ⇐

wikipage modified on 2014/0601/2317