Getting Information about a File or Folder Using the info for Command 221 Try It Out: Writing and Reading a List of Records 229 Using the choose file name Command to Pick a File Name 238
Trang 2Beginning AppleScript®
Stephen G Kochan
Trang 4Beginning AppleScript®
Published byWiley Publishing, Inc
10475 Crosspoint BoulevardIndianapolis, IN 46256-5774
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in Canada
ISBN: 0-7645-7400-0Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 11MA/RX/RR/QU/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections
107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, orauthorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 RosewoodDrive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should beaddressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)572-3447, fax (317) 572-4355, e-mail: brandreview@wiley.com
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY:THE PUBLISHER AND THE AUTHOR MAKE NO RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CRE-ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CON-TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THEUNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF ACOMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THEAUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION
REP-OR WEBSITE IS REFERRED TO IN THIS WREP-ORK AS A CITATION AND/REP-OR A POTENTIAL SOURCE OF THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR-MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVECHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002.Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not beavailable in electronic books
FUR-Library of Congress Cataloging-in-Publication Data:
2004022630
Trademarks:Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer and related tradedress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United Statesand other countries, and may not be used without written permission AppleScript is a registered trademark ofApple Computer, Inc in the U.S and other countries All other trademarks are the property of their respectiveowners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book
Trang 6About the Author
Stephen G Kochan has been developing software and writing books for over 20 years He is the author
and coauthor of several best-selling titles on the C language, including Programming in C and Programming
in ANSI C (both from Sams Publishing), Programming C for the Mac (Macmillan Computer Publishing),
and Topics in C Programming (Wiley Publishing), as well as several Unix titles, including Exploring the
Unix System and Unix Shell Programming (both Sams Publishing), and Unix System Security (Hayden
Books) His most recent title on Mac programming is Programming in Objective-C (Sams Publishing),
which is a tutorial on the primary programming language used on the Mac for application development
Trang 8Mary Beth Wakefield
Vice President & Executive Group Publisher
Graphics and Production Specialists
Carrie Foster, Denny Hager, Joyce Haughey, Jennifer Heleine
Quality Control Technician
John Greenough, Carl William Pierce
Media Development Specialist
Trang 10To my friends Allan, Cesar, Ramon, Lev, and Adrian for always being there
Trang 12Acknowledgments xxv
Introduction 1
Conventions 5
p2p.wrox.com 6
Understanding the Buttons Parameter in the display dialog Command 17
Try It Out: Using the display dialog’s Buttons Parameter 17
Try It Out: Setting the Default Button in a Dialog 19
Trang 13Try It Out: Basic Data Type Conversions with the as Operator 44
Trang 14Contents
Try It Out: Testing the Various Relational Operators 72
Try It Out: Displaying a Message Based on the Day of the Week 84
Try It Out: Have Some Fun: Get Your Salutation at Log In 93
Try It Out: A Program to Sum the Integers from 1 to n 106
Trang 15Try It Out: Sequencing through the Elements in a List 122
Try It Out: Using considering and ignoring Statements 133
Try It Out: Using Containment Operators and the offset Command 146
Try It Out: Count the Number of Words in Some Text 150
Trang 16Contents
Try It Out: Sequencing through the Items in a List 168 Try It Out: A Program to Display Populations of U.S Cities 169 Try It Out: A Modified Version of the Population Program 172
Try It Out: Looking Up the choose from list Command in the Dictionary 174
Try It Out: Deleting and Inserting items in a List 186
Try It Out: A Version of the Population Program Using Records 200
Trang 17Getting Information about a File or Folder Using the info for Command 221
Try It Out: Writing and Reading a List of Records 229
Using the choose file name Command to Pick a File Name 238
Trang 18Try It Out: Understanding Variable Scope: Protecting a Global Variable 265 Try It Out: Understanding Variable Scope: Local and Global Variables with the
Try It Out: Understanding Variable Scope: Local and Global Variables with the
Try It Out: Understanding Variable Scope: Accessing a Global Variable Declared
Try It Out: Writing a Handler with Labeled Parameters–Form 1 273
Try It Out: Writing a Handler with Labeled Parameters–Form 2 275
Trang 19Try It Out: References to Objects and More on the tell Statement 304
Try It Out: Calling Handlers from within tell Blocks 312 Try It Out: Accessing Properties or Variables from within tell Blocks–Part 1 313 Try It Out: Accessing Properties or Variables–Part 2 314
Try It Out: Adding a Prefix to Each File in a Folder 329
Try It Out: Using Finder Filer References outside a tell Block 332
Trang 20Contents
Try It Out: Making an Album from a Folder of Images 368
Try It Out: Making a DVD Slide Show from a Folder of Images 375
Trang 21Try It Out: Defining Script Objects inside Handlers 397
Try It Out: Illustrating the store script and run script Commands 399
Try It Out: Returning a Script Object from a Handler 402
Try It Out: Calling a Parent’s Handler Using the continue Command 414
Trang 23Contents
Trang 26After all the books I’ve written, you would think I would have this time-management thing down to ascience by now Not a chance! I still haven’t been able to judiciously ration my time so that I don’t end upputting a lot of pressure on myself and the ones around me as I approach my deadline To those around
me who put up with this, I am eternally grateful This includes my wonderful kids, Julia, Linda, andGreg, who were once again unfortunate enough to have their father work on a book during their sum-mer break
My contacts at Wiley were equally patient and professional I’d like to thank my acquisitions editor,Katie Mohr, for her continued support throughout this project My development editor, Jodi Jensen, wasremarkable! Thanks Jodi, for all your hard work and attention to detail It was a real pleasure workingwith you on this book Finally, I’d like to thank Terrence Talbot, my technical editor, for his thoroughness
in reviewing my manuscript
Trang 28The AppleScript language evolved from a revolutionary language called HyperTalk, which wasdeveloped in 1987 by Bill Atkinson HyperTalk, which was part of the programming environmentcalled HyperCard, allowed you to write English-like sentences to accomplish your tasks Several
commercial applications, most notably the popular game Myst, were developed in HyperCard.
However, due to various marketing decisions, HyperCard and HyperTalk never gainedwidespread popularity and support
Like HyperTalk, AppleScript remained a language embraced by a relatively small circle of asts With the surge in popularity of Mac OS X, a powerful operating system based on UNIX, came asurge in the popularity of AppleScript This was partly due to the fact that more and more applica-
enthusi-tions became scriptable, meaning you could talk to them from an AppleScript program AppleScript
was also found to be well suited for automating repetitive tasks in the workplace, a process known
as workflow automation Finally, AppleScript’s growth in popularity was partly owed to Apple’s
recog-nition and adoption of AppleScript as a key technology component in Mac OS X
AppleScript is called a scripting language Scripting languages are programming languages
designed primarily to control or coordinate the operation of other programs Examples of otherpopular scripting languages include JavaScript, Perl, Ruby, VBScript, the UNIX shell, and Python
On your Mac, a scripting language might ask the Safari browser to display a particular web page
Or it might ask iTunes to play a particular song Scripting languages are also often used to nate the transfer of data between multiple applications to accomplish a task So a script might con-tain code to go to the website for some data, put it into an Excel spreadsheet, and then email thespreadsheet to your boss
coordi-In the past, scripting languages were not well suited for accomplishing general-purpose ming tasks because they either lacked sufficient programming capabilities or were simply too ineffi-cient However, the line between a scripting language and a general purpose programming languagehas become blurred over the years In some situations, AppleScript can work just fine as a way toimplement a solution to a general programming problem
program-Who This Book Is For
This book is a tutorial on the AppleScript language Most of the existing books on AppleScriptconcentrate on its use in the workplace for workflow automation However, AppleScript is a greatlanguage for the hobbyist and computer enthusiast to learn, and those groups are the intendedaudience for this book Instead of focusing on how to use AppleScript to format data for an Excel
Trang 29spreadsheet, edit some images in PhotoShop, or create a document with FrameMaker, this book showshow easy it is to use AppleScript to control some of the fun applications on your system As a result, theprograms in this book show you how do things like write a simple alarm clock program, create a simpleiTunes player, or take a folder of images and make a DVD slide show.
That’s not to say that programmers who intend to use AppleScript for workflow automation should notread this book This book teaches you what you need to know to get started and how to write yourscripts However, be forewarned: you will be having some fun along the way!
How This Book Is Str uctured
As I just noted, the purpose of this book is to teach you how to write programs in AppleScript It isdesigned to appeal to both the novice and experienced programmer alike and assumes no prior pro-gramming experience Readers with prior programming experience will find that AppleScript has aunique way of doing things that most likely differs significantly from any other programming languageyou have used
The approach taken in this text is to teach by example, using small, well-chosen, complete programmingexamples These are presented using the Wrox trademark “Try It Out” format By typing each example,running it, and examining the results, you gain experience with the entire process of entering, running,and debugging programs Experience has shown that this hands-on approach is one of the most effectiveways to learn
You will find that most of the programs in this book illustrate a specific concept, such as how to write aloop, how to get a list of files, and so on These examples are not designed for industrial use That is,they do not avoid all possible errors in all possible situations In many cases, that would make the pro-grams too hard to follow However, defensive programming is taught in the text, and an entire chapter isdevoted to error handling
At the end of each chapter, you will find exercises To gain maximum benefit from this book, I stronglysuggest that you work through each exercise before proceeding to the next chapter Not only will thishelp to solidify the concepts presented in the chapter, but also it will help prepare you for the materialcovered in the following chapter Answers to the exercises are supplied in Appendix A, but I urge you tofirst try solving the problems on your own before you consult the appendix
Here’s a rundown of what you’ll find in the each chapter:
In Chapter 1, “Writing You First AppleScript Program,” you waste no time getting started Right off thebat, I show you how to start up the Script Editor application, type in a program, and run the program tosee your results The chapter then shows you how to write a program that puts up a simple dialog usingthe display dialogcommand You use this command extensively throughout the book
Chapter 2, “Variables, Classes, and Expressions,” covers some of the more mundane aspects of the guage, but these are concepts you need to learn to master the language In this chapter, you learn the rulesfor forming variable names, writing arithmetic expressions, and working with many of AppleScript’sbuilt-in classes One unique aspect of AppleScript is its support for a built-in date class, which allows you
lan-to easily work with dates in your programs
Introduction
Trang 30In Chapter 3, “Making Decisions,” you learn how to use the ifstatement to make comparisons andaffect the flow of control in your program based on the result of your comparisons In this chapter, youalso learn how to get input from the user.
Chapter 4, “Program Looping,” covers the many forms of AppleScript’s repeatstatement This is thefundamental statement for repeatedly executing a group of statements You see how to write a simpleguessing game program that allows a user to try to guess a number between 1 and 10 that has been randomly selected by your program
In Chapter 5, “Working with Strings,” I show you how to work with character strings You learn how toget elements such as characters and words from a string, how to get the length of a string, and how tocompare two strings
Chapter 6 is titled “Working with Lists and Records.” List and Records are the fundamental data tures supported in AppleScript This chapter shows you how to use them effectively in your programs,how to access elements from them, and how to form more complex data structures such as lists contain-ing lists and lists containing records
struc-In Chapter 7, “Working with Files,” you learn about file name paths and POSIX paths The chaptershows you how to use AppleScript’s built-in commands to open a file, read data from it, and write data
to it You also learn how to get information about a file, such as its size, its modification date, and itstype The chapter shows how to use commands to allow a user to choose a file or a folder on the systemand how you can enumerate the contents of a folder in your program
A handler is AppleScript’s equivalent of a function or subroutine in other languages In Chapter 8,
“Handlers,” this topic is covered in detail You learn the different ways you can write a handler, how topass arguments to and return values from a handler, and the differences between local and global vari-ables In this chapter, you also develop a set of handlers for performing common operations with lists
Sometimes errors can occur in your program at unexpected times and in unexpected places In Chapter 9,
“Error Handling,” you learn how to plan for such events and how to intelligently handle them when theyoccur You learn how AppleScript provides a mechanism so that you can “catch” an error when it occursand handle it accordingly
Because AppleScript is a scripting language, it was designed to enable you to easily communicate withother applications This is done primarily through a feature of the language called the tellstatement
In Chapter 10, “Working with Applications,” you learn how to use this statement in detail The Finder isthe primary application illustrated in this chapter You learn how to ask the Finder to do things that youcan’t handle directly in AppleScript, such as renaming, moving, or deleting a file The chapter also
shows you how to write a droplet, which is an application that gets executed whenever someone drops
files onto its icon
Chapter 11, “Scripting iLife Applications,” provides the most fun of any chapter in the book! iLife is asuite of applications that includes iTunes, iPhoto, iDVD, iMovie, and GarageBand Of these five applica-tions, only the first three were scriptable as of the writing of this book In this chapter, you develop asimple application that allows you to prompt the user for a song title and then ask iTunes to play it TheiPhoto example shows you how to create a new album in your photo library from a folder of image files.Finally, The iDVD example shows you how to write an AppleScript program to create a DVD slide showpresentation from a folder of images
3
Introduction
Trang 31Chapter 12, “Script Objects,” goes into detail about script objects, showing you how to store them in afile and subsequently load them into your programs You also learn how defining a script object inside
a handler allows you to write programs that are consistent with an object-oriented programming (OOP)style
Chapter 13, “Loose Ends,” serves the purpose implied by its name: to tie up some loose ends Topicscovered in this chapter are those that are either of a more advanced nature or did not fit neatly into thestructure of earlier chapters These include web services, the Script Menu, GUI scripting, and recordingscripts
Chapter 14 is the last chapter in the book and is titled “Introducing AppleScript Studio.” AppleScriptStudio was released with the Panther version of Mac OS X (v 10.3) AppleScript Studio, makes thebridge between AppleScript and GUI applications With AppleScript Studio, you can develop a sophisti-cated user interface and have AppleScript as the underlying code to respond to events like the clicking
of a button or the movement of a slider Chapter 14 is an introduction to AppleScript Studio and guidesyou through the steps involved in creating a simple application
There are also three appendices provided in this book: Appendix A, “Exercise Answers,” provides tions for the exercises presented in the text Appendix B, “Language Reference,” provides a quick refer-ence to AppleScript’s operators and commands Appendix C, “Resources,” contains a list of resources andplaces you can look for more information about AppleScript and some of the tools mentioned in the text
solu-What You Need to Use This Book
This book covers the latest version of AppleScript At the time of this writing, the latest version was1.9.3 You use a separate program to enter and run AppleScript programs On the Mac, Script Editor isthe primary tool used for such purposes The version of Script Editor I cover in this book is 2.0 There areother third-party script editors available for use with AppleScript, including Smile and Script Debugger.These are mentioned throughout the text but are not covered in detail
The chapter covering scripting iLife applications was developed using the following versions: iTunes v4.6,iPhoto v4.0.3, and iDVD v4.0.1 The iLife suite comes preinstalled on many Mac systems Alternatively,you can buy iLife from Apple’s website iTunes is also available for no charge from that website if youdon’t want to purchase the entire iLife suite
The chapter on AppleScript Studio is based on version 1.5 of Xcode The latest version of Xcode can beobtained at no charge from Apple’s website You just need to register there as an online developer, again,
at no cost to you
Although AppleScript is a fairly stable programming language that has not changed much, it is widelyrecommended that you use the latest versions of the software with this book In that way, you areassured that the features used in the examples are supported by the applications being used
All the programs in this book were tested on my Titanium PowerBook G4 running Mac OS X version10.3.5 Compatibility with earlier versions of OS X or the applications cited previously is not guaranteed
Introduction
Trang 32To help you get the most from the text and keep track of what’s happening, we’ve used a number of ventions throughout the book
con-Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles used in the text
❑ We highlight important words when we introduce them
❑ We show keyboard strokes like this: Ctrl-A
❑ We show file and folder names, URLs, and code within the text in a special monofont typeface,like this: persistence.properties
❑ We present code in two different ways:
In code examples we highlight new and important code with a gray background
The gray highlighting is not used for code that is less important in the presentcontext or has been shown before
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or use the source code files that accompany the book All of the source code used in this book is availablefor download at http://www.wrox.com Once at the site, simply locate the book’s title (either by usingthe Search box or by using one of the title lists) and click the Download Code link on the book’s detailpage to obtain all the source code for the book
Because many books have similar titles, you may find it easiest to search by ISBN; for this book the ISBN is 0-7645-7400-0.
After you download the code, just decompress it with your favorite compression tool Alternatively, youcan go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspxto see the code available for this book and all other Wrox books
Errata
We make every effort to ensure that there are no errors in the text or in the code However, no one is fect, and mistakes do occur If you find an error in one of our books, like a spelling mistake or faultypiece of code, we would be very grateful for your feedback By sending in errata you may save anotherreader hours of frustration; at the same time, you are helping us provide higher quality information
per-To find the errata page for this book, go to http://www.wrox.comand locate the title using the Searchbox or one of the title lists Then, on the Book Search Results page, click the Errata link at the bottom of
5
Introduction
Trang 33the book entry On this page, you can view all errata that has been submitted for this book and posted
by Wrox editors A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml
If you don’t spot “your” error on the book’s Errata page, go to www.wrox.com/contact/techsupport.shtmland complete the form there to send us the error you have found We’ll check the informationand, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions
of the book
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com The forums are a Web-based tem for you to post messages relating to Wrox books and related technologies and interact with otherreaders and technology users The forums offer a subscription feature to e-mail you topics of interest ofyour choosing when new posts are made to the forums Wrox authors, editors, other industry experts,and your fellow readers are present on these forums
sys-At http://p2p.wrox.comyou will find a number of different forums that will help you not only asyou read this book, but also as you develop your own applications To join the forums, just follow thesesteps:
1. Go to p2p.wrox.comand click the Register link
2. Read the terms of use and click Agree.
3. Complete the required information to join as well as any optional information you want to vide and click Submit
pro-4. You will receive an e-mail with information describing how to verify your account and complete
the joining process
You can read messages in the forums without joining P2P but in order to post your own messages, you must join.
After you join, you can post new messages and respond to messages other users post You can read sages at any time on the Web If you would like to have new messages from a particular forum e-mailed
mes-to you, click the Subscribe mes-to this Forum icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks To read the FAQs, click the FAQ link on any P2P page
ques-Introduction
Trang 34Writing Your F ir st AppleScript Program
There’s no point in wasting time You are reading this book because you want to learn how towrite programs in AppleScript So instead of wading through theory and terminology, I want you
to begin by typing an AppleScript program, running it, and looking at the results I introduce minology as it is necessary along the way If you begin this way, you’ll have more fun and youwon’t get overwhelmed
ter-Star ting with Script Editor
Your Mac OS X system comes with some preinstalled tools that you’ll be using in this book One ofthe most useful ones (as far as AppleScript programming goes) is an application called ScriptEditor This application allows you to enter, compile, debug, and run your AppleScript programs
in an interactive environment It is a simple and effective tool
The Script Editor application is stored in your Applicationsfolder inside a subfolder called
AppleScript Its icon looks like the one shown in Figure 1-1
Figure 1-1
Trang 35Locate the Script Editor application and double-click it to start it You should get a window on your screenthat looks similar to the one shown in Figure 1-2 This window is where you type your AppleScript pro-gram I show you how in the following Try It Out.
Figure 1-2
Try It Out Typing Your First Program
Click inside the Script Editor window and type the following:
100 * pi
Your window should look like Figure 1-3
Chapter 1
Trang 36Figure 1-3
Compiling and Running Your Program
Try It Out Running Your First Program
After typing the indicated line in the window, move your pointer to the top of the window and click thebutton labeled Run, as depicted in Figure 1-4
Trang 37char-as well, from Courier to Verdana.
This book is printed in black and white, so you obviously can’t see the colors in Figure 1-5 or in any
screen shots in this text But if you’re following along, you should see these color and font changes on your screen
Script Editor automatically displays any special words, known as keywords, in blue by default (you can
select other colors to use if you like) This is done to visually aid you when you look at your program
As you’ll see later, other colors and font styles are used to indicate program elements such as comments,variables, and operators
At the bottom of the window, you should see the number 314.159265358979(or something very close to it) Congratulations, this number represents the output (or the result) from running your firstAppleScript program!
Chapter 1
Trang 38Make sure that the Result tab button is highlighted at the bottom of the window If it isn’t, click it so that the result of the operation can be seen.
How It Works
When you start up Script Editor, a window labeled Untitled is automatically created for you In this dow you can enter your AppleScript program In the simplest case, a program can simply be an expres-sion to evaluate, as in
win-100 * pi
This expression uses the multiplication operator, which is the asterisk (as it is in every other ming language I know of) to multiply the number 100 by something called pi Recalling your high schoolmathematics, pi or π(as it’s written using mathematical notation) is a number frequently used when per-forming calculations with circles It’s roughly equal to the value 3.14159 As you learn in greater detail inChapter 2, the keyword piis used in AppleScript as an approximation of the value of π
more than just a conformance check.) The result of this compilation process is the translation of
your AppleScript program into another format that is more optimal for execution
❑ Indents your AppleScript code according to certain stylistic rules
❑ Changes the color of your words, operators, and expressions according to certain rules
❑ Runs your program and displays the result in the lower portion of your window, provided noerrors are detected during the compilation phase
Now that you’ve run your first program, you should save it The following Try It Out walks you throughdoing just that
Try It Out Saving Your First Program
Even though this was an extremely simple first program, you should save it anyway
1. Go to the menu bar at the top of your screen and choose File ➪ Save A dialog box like the one
shown in Figure 1-6 appears
11
Writing Your First AppleScript Program
Trang 39Figure 1-6
2. Your dialog box may look a little different based on the files stored on your system and which
version of OS X you’re running In any case, in the box labeled Save As, replace the name
Untitledwith a more meaningful name such as My First AppleScript Program
3. The other settings in the dialog box should remain as shown in Figure 1-6 After entering the file
name, click the Save button This causes your program to be saved to the specified file name
When you go to save your program, Script Editor tries to compile it before saving In that respect, it
forces you to correct any errors before you can save your program to a file
Later, if you want to make changes to your program, you can double-click the file name in the Finder to launch Script Editor with the specified file open Alternatively, if Script Editor is already running, you can open the file for editing by choosing File ➪ Open.
You now know how to start the Script Editor application, type an expression (which represents a completeAppleScript program), compile and run the program, view the results, and save the program to a file
Extending Your F irst Program
You’re not quite finished with your first program In this section, you see how Script Editor reportserrors Then you learn how to add a description to your program and how to use a command that opens
a simple dialog box
Reporting Errors in Your Programs
First, let’s see what happens if you make a mistake Erase the contents of your window (one way is byhighlighting all the text using your mouse and pressing the Delete key)
Chapter 1
Trang 40Now type the following into an empty window:
100 * pie
Click Run to compile and run your program, as you did previously A dialog box like the one shown inFigure 1-7 should appear
Figure 1-7
The Script Editor application is telling you that it doesn’t know about a variable called pie; that is, pie
is not defined You learn about variables shortly; but essentially, a variable is a place in memory that you
assign a name to and use for storing data For now, just click OK to dismiss the dialog box Your windowshould now look like the one shown in Figure 1-8
Figure 1-8
13
Writing Your First AppleScript Program