DekGenius.com
[ Team LiB ] Previous Section Next Section

12.1 Branching

The "intelligent" behavior of a computer program depends upon its ability to make choices at runtime. These choices generally take the form of evaluating some expression and executing a particular set of lines of code depending on how the evaluation turns out at that moment.

One major form of choice is branching. We have a line or block of code that can be executed optionally. The computer evaluates a boolean expression, called a condition. If the condition is true, the line or block of code is executed; if it isn't, the line or block of code is skipped, and execution jumps to the line that follows it.

In AppleScript, branching control is performed with if. There are several forms of if block.

When typing a multiline if block, don't bother to type the word then. AppleScript will add it at compile time.


The basic form is a block of code that is executed only if a condition is true. If the condition is false, the block is skipped, and execution resumes after the end if line.

if condition then
        -- what to do if condition is true
end if

It is also permitted to supply a second block, to be executed if the condition is false. One or the other of the two blocks will be executed.

if condition then
        -- what to do if condition is true
else
        -- what to do if condition is false
end if

Another syntax lets you specify multiple conditions. AppleScript will execute the first block whose condition is true, skipping the others. It is permitted to supply a final block that will be executed if none of the conditions is true.

if condition1 then
        -- what to do if condition1 is true
else if condition2 then
        -- what to do if condition2 is true
-- ... same for condition3, condition4, etc.
[else]
        -- what to do if none of them is true
end if

So, for example:

set x to random number from 1 to 10
set guess to text returned of ¬
        (display dialog "Pick a number from 1 to 10" default answer "")
try
        set guess to guess as number
on error
        return
end try
if guess < 1 or guess > 10 then
        display dialog "I said from 1 to 10!"
else if guess < x then
        display dialog "Too small. I was thinking of " & x
else if guess > x then
        display dialog "Too big. I was thinking of " & x
else
        display dialog "Just right."
end if

There's also a single-line form:

if condition then whatToDo

In the single-line form, whatToDo is any valid expression or single-line command (it can even be another single-line if).

    [ Team LiB ] Previous Section Next Section