Section 19.8. Second-Level Evaluation


19.8. Second-Level Evaluation

By "second-level evaluation " I mean constructing and executing code at runtime. AppleScript has no built-in way of performing second-level evaluation. However, you can achieve much the same effect through the use of the run script scripting addition command, which allows you to compile and run a string. (See "Compiled Script Files as Script Objects" in Chapter 8.)

The use of run script is rather resource-expensive , because it requires that a completely new instance of the AppleScript scripting component be generated and torn down. It's also rather slow, because it takes time to compile the string. Finally, it's rather clunky, because a string run in this way has no communication with its surroundings; indeed, because a new instance of the AppleScript scripting component is generated, it has no surroundings at all. In other words, it isn't like a script object that can "see" globals at the point where it is defined and run.

Nevertheless, there are things you can accomplish with run script that can be accomplished in no other way. For example, all terminology must be resolved at compile time, so the only way to construct completely dynamically, at runtime, a command involving terminology is by means of run script.

In this example, we permit the user to enter part of an expression to be evaluated by saying it to the Finder:

 set d to "window 1" set p to "What Finder object would you like the name of?" set r to display dialog p default answer d set s to text returned of r set s to "tell app \"Finder\" to get name of " & s try     set res to run script s     display dialog res on error     display dialog "Sorry, that didn't work." end try

For another example of run script used for second-level evaluation, see "Record Properties" in Chapter 13.




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

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