DekGenius.com
[ Team LiB ] Previous Section Next Section

11.3 Identifying References

AppleScript goes to some lengths to hide the existence of references, making it remarkably difficult to find out that a value is a reference. Properly speaking, a reference is a class, a datatype like string or integer (Section 10.1 and Chapter 13). If you ask a string about its class, it says string. If you ask an integer about its class, it says integer. But if you ask a reference about its class, it will never tell the truth and say reference.

set x to "hey"
set y to 9
tell application "Finder" to set z to folder 1
class of x -- string
class of y -- integer
class of z -- folder

Here are some tricks you can use to learn that a value is a reference. (I don't guarantee any of them, but they do seem mostly to work.)


The reference coercion trick

The only thing that can be coerced to a reference is a reference. If you try to coerce anything else to a reference, you'll get a runtime error. So try to coerce a value to a reference, and if there's no error, it is a reference. For example:

tell application "Finder" to set x to folder 1
x as reference -- no error; it's a reference

The editor result trick

If the script result, as shown in your script editor program, contains the word of, it is a reference. For example:

tell application "Finder" to set x to folder 1
x -- folder "Mannie" of...; it's a reference

The copy trick

A copy of a reference is the same reference. If you have two copies of something and they both provide access to the same thing (you may have to devise a further test in order to decide this question), they are both references. For example:

tell application "Finder"
        set x to folder 1
        copy x to y
        index of x is index of y and container of x is container of y -- true
end tell

When I'm debugging or developing a script, I like the second method best; I look at a variable's value and I can see right away whether it's likely to be a reference. If I'm writing code where the code itself needs to test whether something is a reference, I like the first method best. Here's a general handler that returns a boolean value telling whether its parameter is a reference:

on isRef(valueToTestAsRef)
        try
                valueToTestAsRef as reference
                return true
        on error
                return false
        end try
end isRef
-- and here's how to call it
tell application "Finder"
        set x to folder 1
end tell
isRef(x) -- true
set x to "haha"
isRef(x) -- false
    [ Team LiB ] Previous Section Next Section