Labels

Auto Hotkey

Labels

A label identifies a line of code, and can be used as a Goto target or to form a subroutine.

LabelName:

To create a label, write the label name followed by a colon as shown above. Aside from whitespace and comments, no other code can be written on the same line.

Names: Label names are not case sensitive, and may consist of any characters other than space, tab, comma and the escape character (`). However, due to style conventions, it is generally better to use only letters, numbers, and the underscore character (for example: MyListView, Menu_File_Open, and outer_loop).

Scope: Each function has its own list of local labels. If a local label has the same name as a global label, the local label takes precedence (and the global label is inaccessible). Some limitations apply when using subroutines within a function.

Target: The target of a label is the next line of executable code. Executable code includes commands, assignments, expressions and blocks, but not directives, labels, hotkeys or hotstrings. In the following example, run_notepad and #n both point at the Run line:

run_notepad:
#n::
    Run Notepad
    return

Execution: Like directives, labels have no effect when reached during normal execution. In the following example, a message box is shown twice - once during execution of the subroutine by Gosub, and again after the subroutine returns:

gosub Label1

Label1:
MsgBox %A_ThisLabel%
return

Subroutines

A subroutine is a portion of code which can be called to perform a specific task. Execution of a subroutine begins at the target of a label and continues until a Return or Exit is encountered. Since the end of a subroutine depends on flow of control, any label can act as both a Goto target and the beginning of a subroutine.

Dynamic Labels

Many commands which accept a label name also accept a variable reference such as %MyLabel%, in which case the name stored in the variable is used as the target. However, performance is slightly reduced because the target label must be "looked up" each time rather than only once when the script is first loaded.

Hotkeys and Hotstrings

Hotkey and hotstring labels are also valid targets for Goto, Gosub and other commands. However, if a hotkey or hotstring has multiple variants, the variant closest to the top of the script is used. All of the hotkey's modifiers or hotstring's options are also part of its label name, but the final double-colon (::) is omitted.

Named Loops

A label can also be used to identify a loop for the Continue and Break commands. This allows the script to easily continue or break out of any number of nested loops.

Functions

Functions can be used in place of labels in a number of cases, including:

The benefits of functions are that they can use local variables, and in some cases (such as Gui control events) they also accept parameters containing useful information.

Related

IsLabel(), A_ThisLabel, Gosub, Goto, SetTimer, Hotkey