Chapter 7. Flow-Control Statements

The flow-control statements in AppleScript orchestrate the “flow” or the order in which the code statements execute in your scripts. Programmers will be familiar with AppleScript’s if conditional statements, which are very similar to the syntax of Visual Basic, Perl, and other languages. These statements execute code only if the tested conditions are true. AppleScript handles loops in script code with several variations of the repeat statement, similar to the “for,” “foreach,” or “for each” statements in other languages. The repeat flow-control construct repeats the execution of code a specified number of times or for each member of a container, such as a list type. Or, it repeats a code phrase a specified number of times:

repeat 100 times...end repeat

You will be pleased to know that AppleScript has more than adequate error-trapping capabilities. This is accomplished by enclosing the statements that may raise errors in a try...end try statement block. In addition, you have already seen dozens of examples of the tell..end tell statement in earlier chapters. These statements specify the objects, usually application objects, that receive the commands or Apple events that your script sends. You specify the targets of different script commands by using these tell statements.

You can nest flow-control statements within other flow-control statements. Most of these statements end, appropriately, with the reserved word end, optionally followed by the ...

Get AppleScript in a Nutshell 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.