Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...