29
votes

Applescript's "choose from list" user interaction has a "cancel" button — I want this "cancel" to tell the script to immediately stop executing. In other words:

 set wmColor to choose from list {"Black", "Black for all", "White", 
     "White for all"} with prompt "What color should the watermark be?" 
     default items "White for all" without multiple selections allowed and 
     empty selection allowed
 if wmColor is false
     *tell script to stop executing*
 end if

Can't seem to find how to do this — does anyone know how?

5

5 Answers

39
votes

Error number -128 is "User Cancelled", and will stop the script - for example:

if wmColor is false then
    error number -128
end if
17
votes

"return" tells a script to stop executing:

display dialog "Do you want to exit this script?" with icon note buttons {"Exit", "Continue"}
if the button returned of the result is "Exit" then
  return
end if
3
votes

For the specific case of an AppleScript invoked via osascript, it can be terminated, returning a status of 0 to the shell, by doing:

tell me to "exit"

Terminate, emitting a message and returning a status of 1, by doing:

tell me to error "{your message}"

The above writes a line like this to standard error:

{scriptname}: execution error: {your message} (-2700)

Here is an example that replaces the cryptic "-2700" and likely does what jefflovejapan is looking for:

tell me to error "Terminated by user" number 0

which writes this to standard error:

{scriptname}: execution error: Terminated by user (0)

and returns a status of 1.

I learned this by experiment, after reading: AppleScript Language Guide - error Statements

1
votes

I found this works well for scripts running within an application (for example, InDesign CS5.5):

repeat 100 times
    tell application ("System Events") to keystroke "." using command down
    delay (random number from 0.5 to 5)
end repeat

This was modified from this answer.

-1
votes

You can use the word "quit" to quit the current application. You can use this if you save your script as an application.

if wmColor is false
    quit
end if