12.5. Handlers Containing Script Objects

You've seen how you can define handlers inside script objects. In the following Try It Out, you learn the opposite.

12.5.1.

12.5.1.1. Try It Out: Defining Script Objects inside Handlers

In the following program, you practice defining a script object inside a handler.

  1. Type the following program into Script Editor:

    -- Script objects defined inside handlers
    
    on callXY()
        script showXY
            property X : 100
    
            set Y to 100
    set X to X + 1
            set Y to Y + 1
    
            log "X = " & (X as string) & ", Y = " & (Y as string)
        end script
    
        run showXY
        run showXY
    end callX
    
    callXY()
    callXY()
  2. Click the Event Log tab and run the program. You get the following four lines of output in the log:

    (*X = 101, Y = 101*)
        (*X = 102, Y = 101*)
        (*X = 101, Y = 101*)
        (*X = 102, Y = 101*)
12.5.1.2. How It Works

The callXY handler is defined to take no arguments. Inside the handler, a script is defined. The showXY script is analogous in function to the script object you defined earlier in this chapter. It defines a property called X with an initial value of 100 and sets and increments a variable called Y.

Because the showXY script is defined inside callXY, the script gets redefined each time the handler is called. That means that the property X is reinitialized each time the handler is called. But when the script is run from inside the handler, it does not get reinitialized each time the script is run, as the program illustrates.

The two statements that run the script follow the definition of ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.