Section 8.4. Script Objects as Values


8.4. Script Objects as Values

A script object is a datatype in AppleScript. This means that a variable's value can be a script object. In fact, a script object definition defines exactly such a variable. You can refer to this variable, and get and set its value, just as you would any other variable. Here, we fetch a script object as a value and assign it to another variable:

 script myScript     display dialog "Howdy" end script set x to myScript run x -- Howdy 

You can also assign a new value to a variable whose value is a script object. No law says that this new value must be another script object; you're just replacing the value of the variable, as with any other variable. The original script object is lost if this variable name is your only way of referring to it. So, you could do this if you wanted:

 script myScript     display dialog "Howdy" end script set myScript to 9 display dialog myScript -- 9 

You can assign to a variable whose value is a script object the value of another script object, in effect replacing its functionality with new functionality. Of course, that new functionality must be defined somewhere to begin with. The old functionality is lost if this variable name is your only way of referring to it. For example:

 script sayHowdy     display dialog "Howdy" end script script sayGetLost     display dialog "Get Lost" end script set sayHowdy to sayGetLost run sayHowdy -- Get Lost 

When you use set (as opposed to copy) to set a variable to a value that is a script object, you set the variable by reference (see "Set by Reference" in Chapter 7). So the script object is not copied; the variable's name becomes a new name for the script object, in addition to any existing names for the script object. This fact has two important implications:

  • Setting a variable to a script object with set is extremely efficient, no matter how big the script object may be.

  • If a script object has more than one name, then whatever mutation is performed upon it by way of one name applies to it under its other names as well.

Here's an example:

 script sayHello     property greeting : "Hello"     display dialog greeting     set greeting to "Get Lost" end script set x to sayHello run sayHello -- Hello run x -- Get Lost 

In that example, running the script object sayHello changed the greeting property of sayHello; when we ran the script object x we found that its greeting property had been changed as well. That's because sayHello and x are merely two names for the same thing. And that's because we used set to set x by reference, making its value the very same script object that sayHello was already the name of.




AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net