TweetFollow Us on Twitter

AppleScript Code Libraries

Volume Number: 22 (2006)
Issue Number: 12
Column Tag: AppleScript Essentials

AppleScript Code Libraries

by Benjamin S. Waldie

If you have been reading my columns for a while (prior to my introductory series on scripting different applications), then you may know that I am somewhat of a subroutine handler fanatic. I feel that handlers are an extremely important part of AppleScript development, and that every AppleScripter should be using them quite often. Unfortunately, many AppleScript developers do not.

There are many benefits to using handlers in a script. Let's discuss a few of these briefly. Handlers provide a mechanism for modularizing AppleScript code into generic chunks, which can be called from multiple locations within a script. This can lead to more efficient script writing. Instead of spending time writing virtually the same code over and over again throughout a script, you can instead focus more time on writing a solid and reliable handler, which can be called numerous times throughout the script. Not only does this help to cut down on the total amount of code you need to write in a script, but it also helps to provide a more focused completed script. Because multiple sections of the script call the same handler code, there are typically fewer areas to troubleshoot if problems do occur during execution. Furthermore, if written modularly enough, it may even be possible to extract a handler from a script, and plug it into other scripts, potentially reducing script writing time in the future too. This leads me into the main focus of this month's column, AppleScript code libraries.

What is an AppleScript Code Library

What exactly is an AppleScript code library? An AppleScript code library, aka a script library, is an AppleScript file that contains pieces of code, usually handlers, which may be loaded and accessed by another script during its execution. AppleScript code libraries provide an excellent way to organize generic chunks of code, to be called by one or more scripts.

For example, suppose you often write scripts that automate tasks in QuarkXPress. The odds are probably pretty good that many of these scripts will perform similar tasks, and many may use similar or identical code. If this were the case, it would make sense to write much of your Quark code as generic handlers, which can then be merged together into a single script file to form a script library. This library of Quark handlers could then be saved into a central location, and then loaded by other scripts in the future, which can then call its handlers as needed.

Building a Script Library

Building a script library is really as straightforward as creating any AppleScript file. There aren't really any hardcore requirements. A script library will often contain handlers, but it doesn't need to. It can contain any thing that any other script can contain, including properties, globals, a run handler, etc. A script library can even load other script libraries.

Preparing to Follow Along

The example code that we will explore throughout this month's column will involve calling code within a script library file. To follow along with these examples, you'll need to create a script library file. Begin by creating a new Script Editor document, and entering the following code.

property someProperty : "Property Value"
display dialog "Running..."
on someHandler()
   display dialog "Handler executing..."
end someHandler
on displayProperty()
   display dialog someProperty
end displayProperty

As you can see, this code that will make up our script library contains a property, some run handler code, and some subroutine handlers. We will walk through the process of accessing each of these elements in our script library from within another script.

Next, we need to save our script library. To do this, just save the Script Editor document as a compiled script to your desktop, and name it My Library.scpt.

Loading a Script Library

Now that we have created our script library, we are ready to begin accessing it from another script. To do this, we will make use of a command that is included in the Scripting Commands suite of the Standard Additions scripting addition, called load script. The load script command accepts one direct parameter, a reference to a script file to be loaded. For example:

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
load script theLibraryPath
--> "script"

If you run the above example code, you will find that, in Script Editor's result pane, the result of the load script command is a reference to the newly loaded script library. Like any other result, this reference may be placed into a variable, for later reference throughout your script. For example:

set theLoadedScript to load script theLibraryPath

Types of Scripts that May Be Loaded

Momentarily, we will explore what you can do once you have loaded a script library file. However, I first want to mention the types of script library files that may be loaded. The load script command may be used to load compiled script files, script applications, script bundles, and script application bundles. It may not be used to load scripts that have been saved in text format. Also, if you are using an older version of Mac OS X (pre-10.3.x), then you will not be able to load script bundles or script application bundles. The ability to load these types of scripts was not possible prior to AppleScript version 1.9.2 in Mac OS X 10.3.

Running a Script Library

So, now that we have loaded a script library file, what do we do with it? One thing that we can do with it is run it. This can be done by simply telling the loaded script to run. For example:

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
tell theLoadedScript to run
--> {button returned:"OK"}

If you test this example code, then you will find that telling the loaded script to run will result in the execution of any code located within the loaded script's run handler. See figure 1.



Figure 1. Running a Loaded Script Library

You will also find that, if the run handler of the loaded script produces a result, then that result will be passed back to the loading script as the result of the run command.

There are actually several syntactical variations to running a loaded script. Another way is to use the run command, followed by a reference to the loaded script as a direct parameter. For example:

run theLoadedScript

Yet another way to run a loaded script is to make use of the run script command, which is also found in the Scripting Commands suite in the Standard Additions scripting addition. This command is also followed by a reference to the loaded script as its direct parameter.

run script theLoadedScript

When using the run script command, it's also not actually necessary to load the script prior to running it. The run script command itself may be passed the path to a script file as its direct parameter. This will cause the script file to be loaded and run, all in one shot, as demonstrated here:

run script theLibraryPath

Calling Handlers within a Script Library

While running a loaded script is great, and can sometimes be very useful, the real power comes with the ability to trigger handlers within loaded script libraries. Once a script has been loaded, any of its handlers are at your disposal, and may be called as needed, throughout the loading script.

Handlers in a loaded script are called much in the same way that local handlers are called within a script. Unlike local handlers, however, they must just be directed to the loaded script. Often, this is done through the use of a simple tell statement. In other words, the loading script tells the loaded script to execute a specific handler. For example:

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
tell theLoadedScript to someHandler()
--> {button returned:"OK"}

If you run the previous example code, you will find that the someHandler() handler within the loaded script is executed, as indicated by the dialog the handler displays. See figure 2.



Figure 2. Calling a Handler in a Loaded Script Library

As an alternative to using a tell statement to call a handler within a loaded script, another equally acceptable method is the following, which will perform in exactly the same manner as the previous example.

someHandler() of theLoadedScript

Accessing Properties within a Script Library

Referencing Properties in a Script Library

As one might expect, if a loaded script contains properties, then those properties may be accessed by any code, such as handlers, within the loaded script. For example, here is some example code that will execute a handler within our loaded script. This handler will display the value of a property in the loaded script. See figure 3.

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
tell theLoadedScript to displayProperty()



Figure 3. Calling a Handler in a Loaded Script, to Display a Property Value

Properties within a loaded script may also be accessed by the loading script. This is done similarly to the process of calling handlers in a loaded script from within the loading script. For example:

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
someProperty of theLoadedScript
--> "Property Value"

Modifying Properties in a Script Library

As you may know, when utilized in a script application, properties are persistent between executions of the script. In other words, if you modify the value of a property within a script application, then the modified property value will be retained until the property is modified again, or until the script is recompiled. Upon a recompile, the property will revert to its original value.

Properties in loaded scripts are handled slightly differently. If you modify a property in a loaded script, the modified property value will be retained as long as the script remains loaded. However, the next time the script is loaded, it will revert back to its original value. The modified property value is not retained between loads. This can be demonstrated via the following example code.

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
tell theLoadedScript to displayProperty()
set someProperty of theLoadedScript to "New Property Value"
tell theLoadedScript to displayProperty()

If you run the example code above, you will find that the displayProperty() handler will be called twice. Once, immediately after the script has been loaded, and again, after the value of the property someProperty has been modified to a new value. The first time the displayProperty() handler is called, it will display a dialog indicating the property's original value, shown previously in figure 3. The second time the handler is called, it will display a dialog indicating the property's new value, showing that the property's value has actually been changed. See figure 4.



Figure 4. Calling a Handler in a Loaded Script, to Display a Modified Property Value

Now, to demonstrate that the modified property value is not retained between loads, try running the previous example code a second time. When you do this, you will find that the first time the displayProperty() handler is called, it displays the original unmodified value for property someProperty.

Storing a Modified Script Library

However, it is actually possible to retain a modified property value within a loaded script. To do this, the loaded script must be stored back into itself after the property has been modified. This is done using the store script command, which is found in the Scripting Commands suite in the Standard Additions scripting addition. For example:

set theLibraryPath to alias ((path to desktop folder as string) & "My Library.scpt")
set theLoadedScript to load script theLibraryPath
tell theLoadedScript to displayProperty()
set someProperty of theLoadedScript to "New Property Value"
store script theLoadedScript

In the example code above, notice that, while we have specified the loaded script to be stored, we have not specified where it should be stored. When the store script command is used with only a direct parameter, the script to be stored, you will be prompted to specify where the loaded script is to be stored. See figure 5.



Figure 5. Storing a Script Using a Specified Name and Location

To store the script back to its original file path, we can specify a file path for the store script command's optional in labeled parameter. For example:

store script theLoadedScript in theLibraryPath

When used in this manner to store a script back to its original path, the store script command will attempt to overwrite the existing script file. Because of this, another dialog will be displayed, asking whether the existing file should be replaced. See figure 6.



Figure 6. Storing a Script With or Without Replacing an Existing Script

To allow the loaded script to be stored back to its original path without displaying this dialog, we can make use of another optional labeled parameter for the store script command, replacing. For example:

store script theLoadedScript in theLibraryPath with replacing

Running this example code will now result in our loaded script being stored back to its original path, with no dialog being displayed. If you now load the script again and call the displayProperty() handler, you will find that the new property value has been retained. The modified property value will continue to be retained until it is modified again, or until the script library file is opened and recompiled.

In Closing

Hopefully, you're starting to see the benefits of using script libraries, especially for sharing subroutine handlers among multiple scripts. The example code throughout this column should provide you with a good foundation for starting to create and access your own libraries. Once you feel comfortable using the techniques that we have discussed, you may want to consider exploring some other interesting ways of utilizing script libraries.

Try saving a script library as a stay opened application and pre-launching it to reduce loading time. Then, allow multiple scripts to call the code within the running script library. Also, we've discussed accessing properties in loaded scripts. For extra credit, try also exploring how globals work in loaded libraries. Can globals be shared between the loading script and the loaded script? Perform some tests on your own to find out.

Until next time, keep scripting!


Ben Waldie is the author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from <http://www.spiderworks.com>, as well as an AppleScript Training CD, available from <http://www.vtc.com>. Ben is also president of Automated Workflows, LLC, a company specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit <http://www.automatedworkflows.com>, or email Ben at <ben@automatedworkflows.com>.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

WhatsApp 2.2136.10 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Thunderbird 91.1.1 - Email client from M...
As of July 2012, Thunderbird has transitioned to a new governance model, with new features being developed by the broader free software and open source community, and security fixes and improvements... Read more
Direct Mail 5.9.1 - Create and send grea...
Direct Mail is an easy-to-use, fully-featured email marketing app purpose-built for macOS. Create, send, and track great looking email campaigns that get results. Start your newsletter by selecting... Read more
LibreOffice 7.2.1.2 - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
Steam 2.0 - Multiplayer and communicatio...
Steam is a digital distribution, digital rights management, multiplayer and communications platform developed by Valve Corporation. It is used to distribute a large number of games and related media... Read more
Adobe Acrobat DC 21.007.20091 - Powerful...
Acrobat DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat DC with Adobe Document Cloud services is... Read more
Carbon Copy Cloner 6.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
Adobe Animate 21.0.9 - Animation authori...
Adobe Animate is available as part of Adobe Creative Cloud for as little as $20.99/month (or $9.99/month if you're a previous Flash Professional customer). Adobe Animate (was Flash CC) lets you share... Read more
Vivaldi 4.2.2406.44 - An advanced browse...
Vivaldi is a browser for our friends. We live in our browsers. Choose one that has the features you need, a style that fits and values you can stand by. From the look and feel, to how you interact... Read more
Adobe Acrobat Reader 2021.007.20091 - Vi...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more

Latest Forum Discussions

See All

PUBG New State crosses 40 million pre-re...
PUBG New State has received over 40 million pre-registrations on both Android and iOS, Krafton has recently announced. The futuristic, sci-fi PUBG Mobiletitle is all set to launch later this year, in October. [Read more] | Read more »
A Mere Husk of a Human Being – The Touch...
In this week’s episode of The TouchArcade Show I continue to be more or less out of my mind due to the exhaustion of having a newborn baby. Yes, I’ve been through all this before with our previous child, but somehow this is kicking my ass even worse... | Read more »
TouchArcade Game of the Week: ‘Night in...
I have said this probably dozens of times over the years, but there are tons and tons of cool video games on non-mobile platforms that people gush about all the time, and I always tell myself “I’ll definitely get around to playing that myself on [... | Read more »
SwitchArcade Round-Up: ‘Ni no Kuni II’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 17th, 2021. In today’s article, we finish our look at the new games of the week with the Friday releases. Some fairly big games in the list today, like Ni no Kuni II:... | Read more »
‘LEGO Star Wars Battles’ from TT Games a...
Last month, LEGO Star Wars Battles () was revealed for Apple Arcade. | Read more »
COD Mobile: The 5 best SMGs in the game
COD Mobile is often lauded for its vast array of weapons and elaborate customization. With every update, the guns get some kind of nerfs or buffs. Regardless of that, SMGs remain popular with players for close to mid-range combat. [Read more] | Read more »
SEGA Will Reveal a New Mobile RPG at Tok...
A few days ago, there was a bit of buzz around the listing of a new RPG under SEGA / Atlus for Tokyo Game Show 2021. Tokyo Game Show 2021 begins later this month and both SEGA and Atlus will have games and updates to showcase. SEGA will be revealing... | Read more »
‘Castlevania: Grimoire of Souls’ and ‘Te...
This week’s Apple Arcade roundup has updates to four amazing games on the service and the addition of two new games. The first new game is Castlevania: Grimoire of Souls () from Konami. | Read more »
‘Indies’ Lies’ is a New Roguelike Deck B...
For several years, as the popularity of MegaCrit’s roguelike deck-building game Slay the Spire grew amongst PC gamers, lots and lots of mobile gamers hoped that the game would one day arrive on their mobile devices, where it seemed like a natural... | Read more »
‘Steam Highwayman: Smog & Ambuscade’...
Cubus Games have released a number of interesting gamebooks on mobile for a number of years now, including titles such as Heavy Metal Thunder and The Frankenstein Wars. Now at the end of this month they’ll be adding another to their catalogue with a... | Read more »

Price Scanner via MacPrices.net

This is the final week for Apple’s 2021 Back...
Apple’s Back to School promotion for 2021 continues through September 27, 2021, making this the final full week to take advantage of these offers. As part of this promotion, Apple will include one... Read more
Verizon offers $100 discount on Apple’s new 8...
Verizon has Apple’s new 8.3-inch iPad mini and 9th-generation iPad on sale for $100 off MSRP with an Unlimited service plan. Discount is for 64GB and 256GB cellular-enabled models. The $100 sale... Read more
Apple’s new 9th generation iPad and 8.3-inch...
Amazon is offering preorder discounts on Apple’s new 9th generation iPad and 8.3″ iPad mini (64GB WiFi models) ranging up to $40 off MSRP. Delivery is expected starting September 24th: iPad: – 10″... Read more
Xfinity Mobile offers new Apple iPhone 13 mod...
Xfinity Mobile has Apple’s new iPhone 13 family of smartphones on sale and available for preorder for $300 off MSRP for customers opening a new line of service. No trade-in is required. Cost of the... Read more
Verizon offers free Apple iPhone 13 and iPhon...
Verizon is offering an $800 discount on Apple’s new iPhone 13 and $700 discount on the iPhone 13 mini for new and existing customers with a qualified trade-in. Price of the iPhone 13 will be spread... Read more
Apple Product Announcements, As Of Late, Have...
COMMENTARY: 09.17.21 – If you were left feeling a little, “meh” following Apple’s latest product launch, you’re not alone. On Tuesday — in a pre-recorded virtual event dubbed, “California Streaming... Read more
Verizon offers 25% discount on Apple MagSafe...
Verizon has Apple MagSafe Chargers on sale for 25% off MSRP from 9/16/21 to 9/30/21. Verizon service is not required to take advantage of these savings. With the discount, Verizon’s sale prices are... Read more
Verizon offers $1000 discount on new Apple iP...
Verizon is offering a $1000 discount on Apple’s new iPhone 13 Pro and iPhone 13 Pro Max for new and existing customers with a qualified trade-in. Price of the iPhone 13 Pro will be spread over 24 or... Read more
New at AT&T: Apple iPhone 13 and 13 mini...
We’ve already told you about AT&T’s $1000 discounts on the Apple iPhone 13 Pro and iPhone 13 Pro Max. AT&T now has Apple’s new iPhone 13 and iPhone 13 mini discounted to $700 off MSRP for new... Read more
‘Mac Potpourri’ Story On Apple And Folding Sm...
FEATURE: 09.16.21 – A certain writer has been seemingly thrust into the limelight thanks to an article published last month on MacPrices. The article — a commentary on how Apple must “‘flip’ the... Read more

Jobs Board

Geek Squad *Apple* Consultation Professiona...
**829606BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 001422-Tualatin-Store **Job Read more
Geek Squad Advanced Repair *Apple* Professi...
**831864BR** **Job Title:** Geek Squad Advanced Repair Apple Professional **Job Category:** Store Associates **Store Number or Department:** 000011-Northtown-Store Read more
Geek Squad *Apple* Consultation Professiona...
**831828BR** **Job Title:** Geek Squad Apple Consultation Professional **Job Category:** Store Associates **Store Number or Department:** 000028-Green Bay-Store Read more
Sr Infrastructure Engineer - *Apple* MacInt...
**Sr Infrastructure Engineer - Apple MacIntosh** **Description** At Bank of the West, our people are having a positive impact on the world. We're investing where we Read more
Senior Software Developer - *Apple* (iOS/tv...
**SUMMARY** Hulu's Apple team is seeking an experienced Senior Software Engineer with a passion for mobile applications to join our team in Seattle. Our highly Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.