Pass By Reference

Parameters passed to a handler, and the value returned from a handler, are normally passed by value in AppleScript. This means that a copy of the value is made, and it is the copy that arrives at the destination scope.

But four datatypes—lists, records, dates, and script objects—when they are passed as parameters to a handler, are passed by reference. This means that no copy is made; the handler’s scope and the caller’s scope both end up with access to the very same value, rather as if it were a global. Any change made to the parameter by the handler is also made back in the context of the caller. For example:

on extend(LL)
        set end of LL to "Jack"
end extend
set L to {"Mannie", "Moe"}
extend(L)
L -- {"Mannie", "Moe", "Jack"}

Notice that we didn’t capture the value of the handler call extend( ). The handler extend was able to modify the list L directly. After the call, L has been changed in the caller’s context, even though the caller didn’t change it.

It makes sense that lists, records, dates, and script objects can be passed by reference, since these are the only mutable datatypes—the only datatypes whose values can be modified in place, as opposed to being replaced wholesale. But it is a little odd that they are passed by reference automatically. Passing by reference gives the handler great power over the parameter, which the handler can misuse. To prevent accidents, it is up to you to remember that list, record, date, and script object parameters are passed ...

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.