Properties

A property is a variable that retains its value after a script has run. Even after you have quit and launched a script again, the script retains its property value. A property has global scope throughout a script. You have to define a property with the property keyword (prop for short), followed by a space, a variable name, a colon character (:), and its initial value:

prop runval : 0

The colon can be preceded and followed by a space, which improves code readability. The following AppleScript creates a howmany property, then increments it by one and displays its value each time the script is run:

property howmany : 0
set howmany to howmany + 1
display dialog (howmany as string)

howmany starts out as 0, then keeps a count of how many times the script has been run. It will not be reinitialized to unless the script is recompiled (optionally altered then saved again). You can set a property to any value type, including booleans, lists, records, and strings. It is good form to declare all properties at the top level of a script, since they are global variables that persist from script execution to execution. You cannot declare a property inside of a handler, as the following example shows. The script successfully displays the value of the aPi property (which is the value of the pi predefined variable, a real number), even though the property is declared beneath the display dialog command. It is better practice to declare all properties at the top of a script:

property aList ...

Get AppleScript in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.