8.5. Local Variables

So far, you have not set the values of any variables from inside your handlers. However, as you start to write your own handlers, you'll certainly want to do this. Unless specified otherwise, variables to which you assign values inside a handler are called local variables. That means that such variables can only be accessed directly from within the handler in which they appear; their use is local to the handler.

The next Try It Out program is an extension of the preceding Try It Out, "Returning Values from Handlers."

8.5.1.

8.5.1.1. Try It Out: Local Variables

In this program, instead of adding just two numbers, the program takes a list of numbers as its argument, adds them up, and returns the result.

  1. Type the following program into Script Editor:

    -- sum all the numbers in a list
    
    on listSum(L)
        set theSum to 0
    
        if class of L is list then
            repeat with num in L
                set theSum to theSum + num
            end repeat
           end
    
        return theSum
    end listSum
    
    -- test out the handler
    
    set myNums to {1, 2, 3, 4, 5}
    
    log listSum(myNums)                    -- 1 + 2 + 3 + 4 + 5
    log listSum(rest of myNums)            -- 2 + 3 + 4 + 5
    log listSum({100, 200, 300, 400, 500}) -- literal list
    
    -- Demonstrate local variable
    set theSum to 999
    listSum (myNums)
    log theSum
  2. Click the Event Log tab and run the program. You see the following results in the log:

    (*15*)
    (*14*)
    (*1500*)
    (*999*)
8.5.1.2. How it Works

The definition of the listSum handler is straightforward enough:

on listSum(L) set theSum to 0 if class of L is list then repeat ...

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.