Redeclaration of Variables

Redeclaration of variables is a nasty edge case, testing the limits of the language. Luckily, the compiler mostly stops you from doing it. But there is a great deal of legal nuttiness, especially among declarations at the top level of a script. Essentially AppleScript is hoist with its own petard: having ruled that variables can be declared implicitly, and that global variables exist at top level even when they are declared elsewhere, AppleScript is simply trying to cope coherently with the consequences.

Here are some examples of what happens when you redeclare a variable.

It is a compile-time error to redeclare an implicit global as local:

set x to 5
local x -- compile-time error: Can't declare x as both a local and global variable

It is a compile-time error to redeclare an implicit local as global:

on getX( )
    display dialog x
    global x -- compile-time error: Can't declare x as both a local and global variable
end getX

By the same token, it is a compile-time error to declare a handler parameter as global within the handler:

on myHandler(what)
    global what -- compile-time error: Can't declare x as both a local and global variable
end

It is a compile-time error to redeclare as local a variable declared global in the same scope (except at the top level):

on getX( )
    global x
    local x -- compile-time error: Can't declare x as both a local and global variable
end getX

It is a compile-time error to redeclare as global a variable declared local in the same scope (except at ...

Get AppleScript: The Definitive Guide, 2nd Edition 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.