AppleScript Programming/Basic commands

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

AppleScript is a programming language that is relatively easy to understand and interpret due to its likeness to English. The commands and lines are written in a syntax similar to English. This allows users to accurately guess code when needed.

Contents

[edit] A first script

Alright, let's write our first program! Launch your Script Editor application (in /Applications/Applescript) and type this into your new document:

beep

Then hit the run button.

Shortest applescript.png

Your Mac should now play its default beep sound. You have just learned your first AppleScript command: beep. The above script is the shortest script in AppleScript, or at least the shortest that does something.

[edit] Dialog boxes

But if you're going to write a tool for scripting programs or even a small AppleScript program, you're going to need to learn to do more than to make the computer beep. The next command we will explore is "display dialog". A display dialog command is written like this:

display dialog "the text to display goes here"

This can be used to present information to a user or, as you will find out later, ask for it.

[edit] Setting variables

Another vital command you should learn is the "set" command. The "set" command sets variables to strings, lists, records, and other variable types. Here is a set command in action:

set theVariable to "Support Wikibooks!"

Now, if one wanted to show the user what the text stored in variable "theVariable" was, they could type:

display dialog theVariable

A dialog box would appear with the text "Support Wikibooks!"

Now you know three vital commands and were briefly introduced to strings. More information on strings is in the next module.

[edit] Using variables with strings

You can use a variable and a string in the same display dialog line. They are combined with &

set project to "Wikibooks"
display dialog "Support " & project

[edit] Exercises

Create a program says "Hello [your name]" with [your name] in a variable.

(Answers)

Next: Numbers and strings