DekGenius.com
[ Team LiB ] Previous Section Next Section

12.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 Section 9.6.)

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 Section 13.13.1.

    [ Team LiB ] Previous Section Next Section