Reference as Parameter

You can pass a value that is a reference as a parameter to a handler, and it remains a reference. So, for example:

local x
tell application "Finder"
    set x to folder 1
end tell
on setName(theRef)
    set name of theRef to "Jack"
end setName
setName(x)

That code successfully changes the name of a folder in the Finder.

You can pass as a parameter a reference to anything you can usefully make a reference to. Thus, the reference to operator almost provides a solution to the problem of passing by reference (see Chapter 9):

on doubleRef(theRef)
    set contents of theRef to 2 * theRef
end doubleRef
script s
    property x : 5
    display dialog x
end script
doubleRef(a reference to s's x)
run s -- 10

But this solution is not completely general, and indeed no completely general solution is possible, because you can't usefully make a reference to a local. Also you'll notice that the example worked only because the handler doubleRef knew in advance that it was going to be handed a reference—it explicitly dereferenced the reference in order to change the thing referred to. So passing a reference is a way to allow a handler to change a value in place, but this is not the same thing as passing by reference, and it doesn't work if the value to be changed is a local variable.

The use of a reference as a parameter can permit a handler to perform dynamic targeting. As long as a handler doesn't use any vocabulary that depends on a specific target, it can target an application whose identity is not ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.