Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

scope - Why, in AppleScript, can't you declare references to variables local to handlers?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...