Script Object’s Run Handler

A script object has a run handler (see Chapter 8), which is executed when the script object is told to run. This run handler may be implicit or explicit.

To tell a script object to run its run handler, send the run message to it. You can do this by making the script object the direct object of the run command, or by saying run within a tell block targeting the script object.

If a script object’s run handler is explicit, it is a handler, and rules about handlers apply to it. For example, you can’t define a handler in a script object’s explicit run handler; outside code can’t see a script object defined in a script object’s explicit run handler; and running a script object’s explicit run handler reinitializes any script objects defined within it.

This example demonstrates that a script object defined in a script object’s explicit run handler has no persistence:

script myScript
        on run
                script myInnerScript
                        property x : 10
                end script
                tell myInnerScript
                        set its x to (its x) + 1
                        display dialog its x
                end tell
        end run
end script
run myScript -- 11

That code yields 11 every time it runs.

Note

If a script object has no explicit run handler and has no executable statements in its implicit run handler, telling it to run can have unpredictable consequences. For example, this would be a bad thing to do:

script myScript
end script
run myScript -- stack overflow

This is almost certainly a bug.

Get AppleScript: The Definitive Guide 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.