Variable scope in AHK v2
AHK v2 handles scope a bit differently from v1. In v2, declaring a variable as global outside a function is redundant. It only matters inside a function, where it is required if you want to use the variable outside the function, or if you want to access an existing global variable.
Thus, the script has the following three points.
1. Initialize variables before reading them.
2. To create a new global variable inside a function,
or to write an existing global variable inside a function, declare the variable as global,
inside the function, prior to using it.
3. If a variable in an assume-local function is only read (not written), then it may resolve to a global variable inside the function.
Code: Select all
#Requires AutoHotkey v2.0
window_id := "" ; Global by default; initialize the global variable
F3:: { ; Function is assume-local
MsgBox window_id ; Variable is read; it resolves to existing *global* variable
}
^`:: { ; Function is assume-local
Global window_id ; To write a global variable, *must* declare it as global here
window_id := WinGetID("A") ; Write the global variable
MsgBox window_id ; Read the global variable
}
Nested functions may refer to local and static variables created by an enclosing function.