Chapter 19. Control

Control structures are the basis of a computer program's overall logic and "intelligence." They dictate the flow of a script. They are not commands; they are the signposts that describe how commands should be treated. They tell AppleScript how to decide what command should be executed next, or what to do if a command fails at runtime. They also modify how certain commands and operators are interpreted.

Tip

When typing any block in this chapter, in the termination line just type the word end. AppleScript fills in the missing term after compilation. (So, for example, don't type end if; just type end.) This shortcut saves time and is helpful for confirming that you have correctly structured your blocks.

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 or not executing a particular block 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. An if block comes in several forms. The basic form is a single block of code that is executed ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.