Creating References to Variables

You can't make a reference to a local variable. Well, you can, but if you try to use it you'll get a mysterious error. For example:

local x
set x to {1, 2, 3}
set y to a reference to x
get item 1 of y -- error: Can't make item 1 of x into type reference

But a reference can itself be stored in a local variable:

local y
set x to {1, 2, 3}
set y to a reference to x
get item 1 of y -- 1

You can make a reference to anything that isn't a local, such as a global or a top-level entity:

script myScript
    property x : 5
    set y to a reference to x
    set contents of y to y + 1
    display dialog x
end script
run myScript -- 6

That works just as well from outside of the script object:

script myScript
    property x : 5
    display dialog x
end script
tell myScript
    set y to a reference to its x
    set contents of y to y + 1
    run -- 6
end tell

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.