Why, in AppleScript, can't you declare referen

2019-01-26 22:32发布

问题:

Why can't you declare and use references to variables unless the variable referenced is scoped globally? Please explain the runtime memory or object structure that leads to the following phenomenon:

Script A fails:

on foo()        
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end foo

foo()

Script B succeeds:

on run
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end run

Script C succeeds:

on foo()        
    global l
    set l to {0}
    set lref to a reference to l
    return item 1 of lref
end foo

foo()

See also: How do you efficiently build a list within a handler in AppleScript? and Why Can't AppleScript make firstValue of hash into type reference in this test code?

回答1:

Because a “reference” is the same thing as an object specifier, so you can’t make a reference to something that isn’t (or is contained by something that isn’t) an object as far as AppleScript is concerned.

A global variable is owned by the top-level script object -- it’s really a property with no initializer. (You can also have a reference to a script property; it doesn’t have to be strictly global.)

A local variable, on the other hand, is owned by the call frame of the handler that it’s in, and call frames are not objects in AppleScript, therefore, no references.