Typing Variables are not strictly typed, and do not need to be declared. Variables can take any data type (including scripts and functions). For example: -- create an integer variable called variable1 set variable1 to 1 -- create a text variable called variable2 set variable2 to "Hello" -- create a list variable called variable3 copy {17, "doubleday"} to variable3 -- copy the list items of variable3 into separate variables variable4 and variable5 set {variable4, variable5} to variable3 -- set a variable to an instance of a script set variable6 to script myScript
Scoping A subroutines cannot be called directly from an application tell block. Use of my or of me is required. tell application "Finder" set x to my myHandler() -- or set x to myHandler() of me end tell on myHandler() --commands end myHandler Using the same technique for scripting addition commands can reduce errors and improve performance. tell application "Finder" set anyNumber to my (random number from 5 to 50) end tell
Types and objects A script can define custom data types, or use one of the many built-in classes and objects which are provided by the language and tend to be recognized by scriptable applications. Notable built-in types and objects include: ; Basic objects •
application: used mostly as a specifier for tell statements (tell application "Finder" …) •
script: script objects are containers for scripts; every AppleScript creates a script object when run, and script objects may be created within AppleScripts •
class: meta-object that specifies the type of other objects •
reference: object that encapsulates an unevaluated object specifier that may or may not point to a valid object; can be evaluated on-demand by accessing its contents property ; Standard data objects •
constant:
constant value; language-defined constants include pi, tab and linefeed •
boolean:
Boolean (true/false) value;
subclass of constant •
number:
abstract superclass of integer and real; rarely used directly •
integer:
integer; can be manipulated with built-in mathematical operators •
real:
floating-point (
real) number; can be manipulated with built-in mathematical operators •
date: date and time •
text: before AppleScript 2.0 (Mac OS X 10.4 and below) the text class was distinct from string and Unicode text, and the three behaved somewhat differently; in 2.0 (10.5) and later, they are all synonyms and all text is handled as
UTF-16 ; Containers •
list: ordered list of objects; can contain any class, including other lists and classes defined by applications •
record: keyed list of objects; like a list, except structured as
key–value pairs; runtime keyed access is unsupported; all keys must be compile-time constant identifiers ; File system •
alias: reference to an existing file system object (file or folder); maintains link to file system object if moved or renamed •
file: reference to a file system object; can refer to an object that does not exist •
POSIX file: reference to a file system object, in plain text, using Unix (
POSIX)-style slash (/) notation; not a true data type, as AppleScript automatically converts a POSIX file to an ordinary file ; Miscellaneous •
RGB color: specifies an RGB triplet (in
16-bit high color format), for use in commands and objects that work with colors •
unit types: converts between standard units; for instance, a value can be defined as square yards, then converted to square feet by casting between unit types using the as operator
Block AppleScript supports compound statement code structure via either single or multiple line syntax. The multiple line syntax ends a
code block with a phrase that like end
keyword where
keyword is the statement keyword at the start of the block. For example: -- Simple form tell application "Safari" to activate -- Compound tell application "MyApp" -- commands for app end tell
Script A script object is full object encapsulating methods and data and inheriting data and behavior from a parent script. Script objects can use the same 'tell' constructs that are used for application objects and can be loaded from and saved to files. Runtime performance can be enhanced in some cases by using script objects. A script object is defined as: script scriptName -- commands and handlers specific to the script end script
Loop The loop construct has multiple variations, all using the keyword
repeat. The loop can be exited via
exit repeat. ; Unconditional repeat -- commands to be repeated end repeat ; Repeat a number of times repeat 10 times -- commands to be repeated end repeat ; Conditional For
repeat while, the block is executed as long as a condition evaluates to true. The
repeat until loop is the same except that the block is executed as long as the condition evaluates to false. set x to 5 repeat while x > 0 set x to x - 1 end repeat set x to 5 repeat until x ≤ 0 set x to x - 1 end repeat ; With a variable A variable is initialized to a value and after each execution of the block, the variable is incremented by the step value; 1 if not specified. -- repeat the block 2000 times, i gets all values from 1 to 2000 repeat with i from 1 to 2000 -- commands to be repeated end repeat -- repeat the block 4 times, i gets values 100, 75, 50 and 25 repeat with i from 100 to 25 by -25 -- commands to be repeated end repeat ; Enumerate A variable has the value of each list item as the loop progresses. set total to 0 repeat with loopVariable in {1, 2, 3, 4, 5} set total to total + loopVariable end repeat
Handler A
handler, a variation of the block structure defines a subroutine. ;Function handler on myFunction(parameters...) -- subroutine commands end myFunction ;Folder actions block on adding folder items to thisFolder after receiving theseItems -- commands to apply to the folder or items end adding folder items to ;Run handler on run -- commands end run Handlers can also be defined using "to" in place of "on" and can be written to accept labeled parameters, not enclosed in parens. ;Handler with labeled parameters on rock around the clock display dialog (clock as string) end rock -- called with: rock around the current date ;Handler using "to" and labeled parameters to check for yourNumber from bottom thru top if bottom ≤ yourNumber and yourNumber ≤ top then display dialog "Congratulations! You scored." end if end check --called with: check for 8 from 7 thru 10 There are four types of predefined handlers in AppleScript—run, open, idle, and quit—each of which is created in the same way as the run handler shown above. ;Run handler: Defines the main code of the script, which is called when the script is run. Run handler blocks are optional, unless arguments are being passed to the script. If an explicit run handler block is omitted, then all code that is not contained inside handler blocks is executed as though it were in an implicit run handler. ;Open handler: Defined using "on open theItems". on open theItems repeat with thisItem in theItems tell application "Finder" to update thisItem end repeat end open When a script containing an "open handler' is saved as an applet, the applet becomes a droplet. A droplet can be identified in the Finder by its icon, which includes an arrow, indicating items can be dropped onto the icon. The droplet's open handler is executed when files or folders are dropped onto droplet's icon. References to the items dropped on the droplet's icon are passed to the droplet's script as the parameter of the open handler. A droplet can also be launched the same way as an ordinary applet, executing its run handler. ;Idle handler: A subroutine that is run periodically by the system when the application is idle. on idle --code to execute when the script's execution has completed return 60 -- number of seconds to pause before executing idle handler again end idle An idle handler can be used in applets or droplets saved as stay-open applets, and is useful for scripts that watch for particular data or events. The length of the idle time is 30 seconds by default, but can be changed by including a 'return x' statement at the end of the subroutine, where x is the number of seconds the system should wait before running the handler again. ;Quit handler: A handler that is run when the applet receives a Quit request. This can be used to save data or do other ending tasks before quitting. on quit --commands to execute before the script quits continue quit -- required for the script to actually quit end quit
Comment A
comment can be formatted various ways. A line comment begins with -- or alternatively in later versions (AppleScript 2.0, first released in
Mac OS X Leopard) with . The latter permits an AppleScript script to run as an executable if it begins with a
shebang line #!/usr/bin/osascript. For example: --This is a line comment • So is this! (in later versions) A block comment (can be multiple lines) is delimited by (* and *). For example: (* This is a multiple line comment *)
User interaction AppleScript has several user interface options, including dialogs, alerts, and list of choices. (The character, produced by typing in the Script Editor, denotes continuation of a single statement across multiple lines.) -- Dialog set dialogReply to display dialog "Dialog Text" default answer "Text Answer" hidden answer false buttons {"Skip", "Okay", "Cancel"} default button "Okay" cancel button "Skip" with title "Dialog Window Title" with icon note giving up after 15 -- Choose from list set chosenListItem to choose from list {"A", "B", "3"} with title "List Title" with prompt "Prompt Text" default items "B" OK button name "Looks Good!" cancel button name "Nope, try again" multiple selections allowed false with empty selection allowed -- Alert set resultAlertReply to display alert "Alert Text" as warning buttons {"Skip", "Okay", "Cancel"} default button 2 cancel button 1 giving up after 2 Each user interaction method can return the values of buttons clicked, items chosen or text entered for further processing. For example: display alert "Hello, world!" buttons {"Rudely decline", "Happily accept"} set theAnswer to button returned of the result if theAnswer is "Happily accept" then beep 5 else say "Piffle!" end if == Open Scripting Architecture ==