Chapter 11. AppleScript Subroutines

IN THIS CHAPTER

  • What are subroutines?

  • Defining a subroutine

  • Running a subroutine

  • Using loops, conditionals, and variables in subroutines

  • Recursive subroutines

  • Reusing subroutines

  • Some useful subroutines

So far, your AppleScript education has included learning about variables, operators, conditional statements, loops, and a few other details. However, you've only created simple scripts that run as standalone files — you haven't had the opportunity to create any scripts that are more complex, or any script that would require reusable code.

In this chapter, you're going to learn how to create and use (and reuse) subroutines to your advantage. Learning about subroutines will take your AppleScript knowledge to the next level.

Please note that many books on AppleScript refer to subroutines as handlers. Technically speaking, they're absolutely correct, but please note that in the AppleScript world, handlers can mean a lot of different things. For example, when you tell an application such as Safari to open, you're using an on handler.

Combining the on handler with a custom handler (or subroutine) that you've built yourself seems a bit confusing, especially if you have experience with shell scripting, Perl, Python, or Java, where custom subroutines are really a separate deal. For that reason, I insist on calling a custom handler a subroutine, just to avoid any possible confusion and to make it easier for programmers from other languages.

What Are Subroutines?

If you're ...

Get Apple® Automator with AppleScript® Bible 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.