Variables and Expressions
From Auto Hotkey
Variables and Expressions
Table of Contents
Variables
See Variables for general explanation and details about how variables work.
Storing values in variables: To store a string or number in a variable, use the colon-equal operator (:=) followed by a number, quoted string or any other type of expression. For example:
MyNumber := 123 MyString := "This is a literal string." CopyOfVar := Var
Variables which have not been assigned a value contain an empty string by default. Therefore, to erase the contents of a variable, simply assign an empty string:
MyVar := ""
A variable can also be assigned a value indirectly, by using it as an output variable of a function. For example:
MouseGetPos x, y
Retrieving the contents of variables: To include the contents of a variable in a string, use concatenation or Format. For example:
MsgBox "The value of Var is " . Var . "." MsgBox "The value in the variable named Var is " Var "." MsgBox Format("Var has the value {1}.", Var)
Sub-expressions can be combined with strings in the same way. For example:
MsgBox("The sum of X and Y is " . (X + Y))
Comparing variables: Please read the expressions section below for important notes about the different kinds of comparisons.
Expressions
See Expressions for a structured overview and further explanation.
Expressions are used to perform one or more operations upon a series of variables, literal strings, and/or literal numbers.
Variable names in an expression are not enclosed in percent signs (except for variables inside quoted strings, and pseudo-arrays and other double references). Consequently, literal strings must be enclosed in double quotes to distinguish them from variables. For example:
if (CurrentSetting > 100 or FoundColor <> "Blue")
MsgBox "The setting is too high or the wrong color is present."
In the example above, "Blue" appears in quotes because it is a literal string. Single-quote marks (') and double-quote marks (") function identically, except that a string enclosed in single-quote marks can contain literal double-quote marks and vice versa. Therefore, to include an actual quote mark inside a literal string, escape the quote mark or enclose the string in the opposite type of quote mark. For example:
MsgBox "She said, `"An apple a day.`"" MsgBox 'She said, "An apple a day."'
Empty strings: To specify an empty string in an expression, use an empty pair of quotes. For example, the statement if (MyVar <> "") would be true if MyVar is not blank.
Storing the result of an expression: To assign a result to a variable, use the := operator. For example:
NetPrice := Price * (1 - Discount/100)
Boolean values: When an expression is required to evaluate to true or false (such as an IF-statement), a blank or zero result is considered false and all other results are considered true. For example, the statement if ItemCount would be false only if ItemCount is blank or 0. Similarly, the expression if not ItemCount would yield the opposite result.
Operators such as NOT/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false. However, the AND/OR operators always produce one of the input values. For example, in the following expression, the variable Done is assigned 1 if A_Index is greater than 5 or the value of FoundIt in all other cases:
Done := A_Index > 5 or FoundIt
As hinted above, a variable can be used to hold a false value simply by making it blank or assigning 0 to it. To take advantage of this, the shorthand statement if Done can be used to check whether the variable Done is true or false.
In an expression, the keywords true and false resolve to 1 and 0. They can be used to make a script more readable as in these examples:
CaseSensitive := false ContinueSearch := true
Integers and floating point: Within an expression, numbers are considered to be floating point if they contain a decimal point or scientific notation; otherwise, they are integers. For most operators -- such as addition and multiplication -- if either of the inputs is a floating point number, the result will also be a floating point number.
Within expressions and non-expressions alike, integers may be written in either hexadecimal or decimal format. Hexadecimal numbers all start with the prefix 0x. For example, Sleep 0xFF is equivalent to Sleep 255. Floating point numbers can optionally be written in scientific notation, with or without a decimal point (e.g. 1e4 or -2.1E-4).
Within expressions, unquoted literal numbers such as 128, 0x7F and 1.0 are converted to pure numbers before the script begins executing, so converting the number to a string may produce a value different to the original literal value. For example:
MsgBox(0x7F) ; Shows 128 MsgBox(1.00) ; Shows 1.0
Operators in Expressions
See Operators for general information about operators.
Except where noted below, any blank value (empty string) or non-numeric value involved in a math operation is not assumed to be zero. Instead, it is treated as an error, which causes that part of the expression to evaluate to an empty string. For example, if the variable X is blank, the expression X+1 yields a blank value rather than 1.
Expression Operators (in descending precedence order)
| %Expr% |
Evaluates the sub-expression Expr and uses its value as the name or partial name of a variable or function. This allows the script to refer to a variable or function whose name is not written literally in the script, but is determined by evaluating Expr, which is typically another variable. Percent signs cannot be used directly within Expr due to ambiguity, but can be nested within parentheses. Otherwise, Expr can be any expression.
If the variable does not already exist, a blank variable is created. An exception is thrown if the name is invalid. This is most commonly used to reference pseudo-array elements such as in the following example: Loop 4
MsgBox("IP address " A_Index " is " A_IPAddress%A_Index%)
Although this is historically known as a "double-deref", this term is inaccurate when Expr does not contain a variable (first deref), and also when the resulting variable is the target of an assignment, not being dereferenced (second deref). |
| x.y | Member access. Get or set a value or call a method of object x, where y is a literal name. See object syntax. |
| new | new Class or new Class(Params) creates a new object derived from Class. For example, x := new y is often equivalent to x := {base: y}. Class can be almost any expression which produces a class object, but is typically a class name such as GlobalClass or GlobalClass.NestedClass. More complex cases such as new new (getClass())(params1)(params2) are also supported, but there must be no space between the class expression and parameter list. For details, see Custom Objects. |
| ++ -- |
Pre- and post-increment/decrement. Adds or subtracts 1 from a variable. The operator may appear either before or after the variable's name. If it appears before the name, the operation is performed immediately and its result is used by the next operation. For example, |
| ** |
Power. Both the base and the exponent may contain a decimal point. If the exponent is negative, the result will be formatted as a floating point number even if the base and exponent are both integers. Since ** is of higher precedence than unary minus, Note: A negative base combined with a fractional exponent such as |
| - ! ~ & |
Unary minus (-): Inverts the sign of its operand. Unary plus (+): Logical-not (!): If the operand is blank or 0, the result of applying logical-not is 1, which means "true". Otherwise, the result is 0 (false). For example: Bitwise-not (~): This inverts each bit of its operand. If the operand is a floating point value, it is truncated to an integer prior to the calculation. As 64-bit signed integers are used, a positive input value will always give a negative result and vice versa. For example, Address (&): |
| * / // |
Multiply (*): The result is an integer if both inputs are integers; otherwise, it is a floating point number. Other uses: The asterisk (*) symbol is also used in variadic function calls. True divide (/): True division yields a floating point result even when both inputs are integers. For example, Floor divide (//): The double-slash operator uses high-performance integer division if the two inputs are integers. For example, The *= and /= operators are a shorthand way to multiply or divide the value in a variable by another value. For example, Division by zero yields a blank result (empty string). |
| + - |
Add (+) and subtract (-). On a related note, the += and -= operators are a shorthand way to increment or decrement a variable. For example, Other uses: If the + or - symbol is not preceded by a value (or a sub-expression which yields a value), it is interpreted as a unary operator instead. |
| << >> |
Bit shift left (<<) and right (>>). Example usage: Value1 << Value2. Any floating point input is truncated to an integer prior to the calculation. Shift left (<<) is equivalent to multiplying Value1 by "2 to the Value2th power". Shift right (>>) is equivalent to dividing Value1 by "2 to the Value2th power" and rounding the result to the nearest integer leftward on the number line; for example, -3>>1 is -2. |
| & ^ | |
Bitwise-and (&), bitwise-exclusive-or (^), and bitwise-or (|). Of the three, & has the highest precedence and | has the lowest. Any floating point input is truncated to an integer prior to the calculation. Related: Bitwise-not (~) Other uses: If the & symbol is not preceded by a value (or a sub-expression which yields a value), it is interpreted as the address operator instead. |
| . |
Concatenate. A period (dot) with at least one space or tab on each side is used to combine two items into a single string. You may also omit the period to achieve the same result (except where ambiguous such as Var := "The color is " . FoundColor ; Explicit concat Var := "The color is " FoundColor ; Auto-concat Sub-expressions can also be concatenated. For example: A line that begins with a period (or any other operator) is automatically appended to the line above it. The entire length of each input is used, even if it includes binary zero. For example, Other uses: If there is no space or tab to the right of a period (dot), it is interpreted as either a literal floating-point number or member access. For example, |
| ~= | Shorthand for RegExMatch. For example, the result of "abc123" ~= "\d" is 4 (the position of the first numeric character). |
| > < >= <= |
Greater (>), less (<), greater-or-equal (>=), and less-or-equal (<=). If either of the inputs is not numeric (or both are strings), they are compared alphabetically. For example, 2 < "10" is true whereas "2" < "10" is false. The comparison is case sensitive only if StringCaseSense has been turned on. See also: Sort When comparing strings, these operators compare only up to the first binary zero. |
| = == <> != |
Equal (=), case-sensitive-equal (==), and not-equal (<> or !=). The operators != and <> are identical in function. The == operator behaves identically to = except when either of the inputs is not numeric (or both are strings), in which case == is always case sensitive and = is always case insensitive (the method of insensitivity depends on StringCaseSense). By contrast, <> and != obey StringCaseSense. The == operator can be used to compare strings which contain binary zero. All other comparison operators except ~= compare only up to the first binary zero. |
| IS IN CONTAINS |
|
| NOT | Logical-NOT. Except for its lower precedence, this is the same as the ! operator. For example, not (x = 3 or y = 3) is the same as !(x = 3 or y = 3). |
| AND && |
Both of these are logical-AND. For example: In the expression A line that begins with AND/OR/&&/|| (or any other operator) is automatically appended to the line above it. |
| OR || |
Both of these are logical-OR. For example: In the expression x or y, if x is false, the result is y. Otherwise the result is x, and y is not evaluated at all - short-circuit evaluation is applied to enhance performance. Although the result is not limited to boolean 0 and 1, it can be interpreted as a boolean value as with any other expression. In effect, the result is true if either input is true. |
| ?: | Ternary operator. This operator is a shorthand replacement for the if-else statement. It evaluates the condition on its left side to determine which of its two branches should become its final result. For example, |
| := += -= *= /= //= .= |= &= ^= >>= <<= |
Assign. Performs an operation on the contents of a variable and stores the result back in the same variable. The simplest assignment operator is colon-equals (:=), which stores the result of an expression in a variable. For a description of what the other operators do, see their related entries in this table. For example, Unlike most other operators, assignments are evaluated from right to left. Consequently, a line such as If an assignment is used as the input for some other operator, its value is the variable itself. For example, the expression The precedence of the assignment operators is automatically raised when it would avoid a syntax error or provide more intuitive behavior. For example: |
| , | Comma (multi-statement). Commas may be used to write multiple sub-expressions on a single line. This is most commonly used to group together multiple assignments or function calls. For example: Note: A line that begins with a comma (or any other operator) is automatically appended to the line above it. See also: comma performance. Comma is also used to delimit the parameters of a function call or control flow statement. To include a multi-statement expression in a parameter list, enclose it in an extra set of parentheses. For example, |
The following types of sub-expressions override precedence/order of evaluation:
| (expression) | Any sub-expression enclosed in parentheses. For example, |
Mod |
Function call. The function name must be immediately followed by an open-parentheses, without any spaces or tabs in between. For details, see Functions. |
%func%() |
See Dynamically Calling a Function. |
| Fn(Params*) | Variadic function call. Params is an array (object) containing parameter values. |
| x[y] [a, b, c] |
Member access. Get or set a value or call a method of object x, where y is a parameter list (typically an array index or key) or an expression which returns a method name. Array literal. If the open-bracket is not preceded by a value (or a sub-expression which yields a value), it is interpreted as the beginning of an array literal. For example, See array syntax and object syntax for more details. |
| {a: b, c: d} | Object literal. Create an object or associative array. For example, |
Performance: The comma operator is usually faster than writing separate expressions, especially when assigning one variable to another (e.g. x:=y, a:=b). Performance continues to improve as more and more expressions are combined into a single expression; for example, it may be 35% faster to combine five or ten simple expressions into a single expression.
Built-in Variables
The variables below are built into the program and can be referenced by any script.
See Built-in Variables for general information.
Table of Contents
- Special Characters: A_Space, A_Tab
- Script Properties: command line parameters, A_WorkingDir, A_ScriptDir, A_ScriptName, (...more...)
- Date and Time: A_YYYY, A_MM, A_DD, A_Hour, A_Min, A_Sec, (...more...)
- Script Settings: A_IsSuspended, A_ListLines, A_TitleMatchMode, (...more...)
- User Idle Time: A_TimeIdle, A_TimeIdlePhysical, A_TimeIdleKeyboard, A_TimeIdleMouse
- Hotkeys, Hotstrings, and Custom Menu Items: A_ThisHotkey, A_EndChar, (...more...)
- Operating System and User Info: A_OSVersion, A_ScreenWidth, A_ScreenHeight, (...more...)
- Misc: A_Cursor, A_EventInfo, Clipboard, ClipboardAll, ErrorLevel
- Loop: A_Index, (...more...)
Special Characters
| A_Space | Contains a single space character. |
| A_Tab | Contains a single tab character. |
Script Properties
| A_Args | Read/write: Contains an array of command line parameters. For details, see Passing Command Line Parameters to a Script. |
| A_WorkingDir | Read/write: The script's current working directory, which is where files will be accessed by default. The final backslash is not included unless it is the root directory. Two examples: Use SetWorkingDir or assign a path to A_WorkingDir to change the working directory. The script's working directory defaults to A_ScriptDir, regardless of how the script was launched. |
| A_InitialWorkingDir | The script's initial working directory, which is determined by how it was launched. For example, if it was run via shortcut -- such as on the Start Menu -- its initial working directory is determined by the "Start in" field within the shortcut's properties. |
| A_ScriptDir | The full path of the directory where the current script is located. The final backslash is omitted (even for root directories). |
| A_ScriptName | Read/write: The default title for MsgBox, InputBox, FileSelect, DirSelect and GuiCreate. If not set by the script, it defaults to the file name of the current script, without its path, e.g. MyScript.ahk. |
| A_ScriptFullPath | The full path of the current script, e.g. C:\My Documents\My Script.ahk |
| A_ScriptHwnd | The unique ID (HWND/handle) of the script's hidden main window. |
| A_LineNumber | The number of the currently executing line within the script (or one of its #Include files). This line number will match the one shown by ListLines; it can be useful for error reporting such as this example: Since a compiled script has merged all its #Include files into one big script, its line numbering may be different than when it is run in non-compiled mode. |
| A_LineFile | The full path and name of the file to which A_LineNumber belongs, which will be the same as A_ScriptFullPath unless the line belongs to one of a non-compiled script's #Include files. |
| A_ThisFunc | The name of the user-defined function that is currently executing (blank if none); for example: MyFunction. See also: IsFunc |
| A_ThisLabel | The name of the label (subroutine) that is currently executing (blank if none); for example: MyLabel. It is updated whenever the script executes Gosub/Return or Goto. It is also updated for automatically-called labels such as timers, GUI threads, menu items, hotkeys and hotstrings. However, A_ThisLabel is not updated when execution "falls into" a label from above; when that happens, A_ThisLabel retains its previous value. See also: A_ThisHotkey and IsLabel |
| A_AhkVersion | Contains the version of AutoHotkey that is running the script, such as 1.0.22. In the case of a compiled script, the version that was originally used to compile it is reported. The formatting of the version number allows a script to check whether A_AhkVersion is greater than some minimum version number with > or >= as in this example: if (A_AhkVersion >= "1.0.25.07"). |
| A_AhkPath | For non-compiled scripts: The full path and name of the EXE file that is actually running the current script. For example: C:\Program Files\AutoHotkey\AutoHotkey.exe For compiled scripts: The same as the above except the AutoHotkey directory is discovered via the registry entry HKLM\SOFTWARE\AutoHotkey\InstallDir. If there is no such entry, A_AhkPath is blank. |
| A_IsCompiled | Contains 1 if the script is running as a compiled EXE and an empty string (which is considered false) if it is not. |
Date and Time
| A_YYYY |
Current 4-digit year (e.g. 2004). Synonymous with A_Year. Note: To retrieve a formatted time or date appropriate for your locale and language, use |
| A_MM | Current 2-digit month (01-12). Synonymous with A_Mon. |
| A_DD | Current 2-digit day of the month (01-31). Synonymous with A_MDay. |
| A_MMMM | Current month's full name in the current user's language, e.g. July |
| A_MMM | Current month's abbreviation in the current user's language, e.g. Jul |
| A_DDDD | Current day of the week's full name in the current user's language, e.g. Sunday |
| A_DDD | Current day of the week's abbreviation in the current user's language, e.g. Sun |
| A_WDay | Current 1-digit day of the week (1-7). 1 is Sunday in all locales. |
| A_YDay | Current day of the year (1-366). The value is not zero-padded, e.g. 9 is retrieved, not 009. To retrieve a zero-padded value, use the following: FormatTime(, "YDay0"). |
| A_YWeek | Current year and week number (e.g. 200453) according to ISO 8601. To separate the year from the week, use SubStr. Precise definition of A_YWeek: If the week containing January 1st has four or more days in the new year, it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. |
| A_Hour | Current 2-digit hour (00-23) in 24-hour time (for example, 17 is 5pm). To retrieve 12-hour time as well as an AM/PM indicator, follow this example: FormatTime(, "h:mm:ss tt") |
| A_Min | Current 2-digit minute (00-59). |
| A_Sec | Current 2-digit second (00-59). |
| A_MSec | Current 3-digit millisecond (000-999). To remove the leading zeros, follow this example: Milliseconds := A_MSec + 0. |
| A_Now |
The current local time in YYYYMMDDHH24MISS format. Note: Date and time math can be performed with DateAdd and DateDiff. Also, FormatTime can format the date and/or time according to your locale or preferences. |
| A_NowUTC | The current Coordinated Universal Time (UTC) in YYYYMMDDHH24MISS format. UTC is essentially the same as Greenwich Mean Time (GMT). |
| A_TickCount | The number of milliseconds since the computer was rebooted. By storing A_TickCount in a variable, elapsed time can later be measured by subtracting that variable from the latest A_TickCount value. For example: StartTime := A_TickCount Sleep 1000 ElapsedTime := A_TickCount - StartTime MsgBox ElapsedTime " milliseconds have elapsed." If you need more precision than A_TickCount's 10ms, use QueryPerformanceCounter(). |
Script Settings
| A_IsSuspended | Contains 1 if the script is suspended and 0 otherwise. |
| A_IsPaused | Contains 1 if the thread immediately underneath the current thread is paused. Otherwise it contains 0. |
| A_IsCritical | Contains 0 if Critical is off for the current thread. Otherwise it contains an integer greater than zero, namely the message-check frequency being used by Critical. The current state of Critical can be saved and restored via Old_IsCritical := A_IsCritical followed later by A_IsCritical := Old_IsCritical. |
| A_ListLines | Read/write: Contains 1 if ListLines is enabled. Otherwise it contains 0. |
| A_TitleMatchMode | Read/write: The current mode set by SetTitleMatchMode: 1, 2, 3, or RegEx. |
| A_TitleMatchModeSpeed | Read/write: The current match speed (fast or slow) set by SetTitleMatchMode. |
| A_DetectHiddenWindows | Read/write: The current mode (On or Off) set by DetectHiddenWindows. |
| A_DetectHiddenText | Read/write: The current mode (On or Off) set by DetectHiddenText. |
| A_StringCaseSense | Read/write: The current mode (On, Off, or Locale) set by StringCaseSense. |
| A_FileEncoding | Read/write: The default encoding for various functions; see FileEncoding. |
| A_SendMode | Read/write: The current mode (Event, Input, Play or InputThenPlay) set by SendMode. |
| A_SendLevel | Read/write: The current SendLevel setting (an integer between 0 and 100, inclusive). |
| A_StoreCapsLockMode | Read/write: The current mode (On or Off) set by SetStoreCapsLockMode. |
| A_KeyDelay A_KeyDuration |
Read/write: The current delay or duration set by SetKeyDelay (always decimal, not hex). |
| A_KeyDelayPlay A_KeyDurationPlay |
Read/write: The current delay or duration set by SetKeyDelay for the SendPlay mode (always decimal, not hex). |
| A_WinDelay | Read/write: The current delay set by SetWinDelay (always decimal, not hex). |
| A_ControlDelay | Read/write: The current delay set by SetControlDelay. |
| A_MouseDelay A_MouseDelayPlay |
Read/write: The current delay set by SetMouseDelay (always decimal, not hex). A_MouseDelay is for the traditional SendEvent mode, whereas A_MouseDelayPlay is for SendPlay. |
| A_DefaultMouseSpeed | Read/write: The current speed set by SetDefaultMouseSpeed. |
| A_CoordModeToolTip A_CoordModePixel A_CoordModeMouse A_CoordModeCaret A_CoordModeMenu |
Read/write: The current mode (Window, Client or Screen) set by CoordMode. |
| A_RegView | Read/write: The current registry view as set by SetRegView. |
| A_TrayMenu | Returns a Menu object which can be used to modify or display the tray menu. |
| A_AllowMainWindow | Read/write: Contains 1 if the script's main window is allowed to be opened via the tray icon, or 0 otherwise. For compiled scripts, this variable defaults to 0 but can be overridden by assigning it a value. Setting it to 1 also enables the items in the main window's View menu such as "Lines most recently executed", which allows viewing of the script's source code and other info. The following functions are always able to show the main window when they are encountered in the script at runtime: ListLines, ListVars, ListHotkeys, and KeyHistory. If the script is not compiled, this variable always contains 1 and any attempts to change it are ignored. |
| A_IconHidden | Read/write: Contains 1 if the tray icon is currently hidden or 0 otherwise. The icon can be hidden via #NoTrayIcon or by assigning this variable a false value. |
| A_IconTip | Read/write: Contains the tray icon's tooltip text, which is displayed when the mouse hovers over it. If blank, the script's name is used instead. To create a multi-line tooltip, use the linefeed character (`n) in between each line, e.g. |
| A_IconFile | Blank unless a custom tray icon has been specified via TraySetIcon -- in which case it is the full path and name of the icon's file. |
| A_IconNumber | Blank if A_IconFile is blank. Otherwise, it's the number of the icon in A_IconFile (typically 1). |
User Idle Time
| A_TimeIdle | The number of milliseconds that have elapsed since the system last received keyboard, mouse, or other input. This is useful for determining whether the user is away. Physical input from the user as well as artificial input generated by any program or script (such as the Send or MouseMove functions) will reset this value back to zero. Since this value tends to increase by increments of 10, do not check whether it is equal to another value. Instead, check whether it is greater or less than another value. For example:
if A_TimeIdle > 600000
MsgBox "The last keyboard or mouse activity was at least 10 minutes ago." |
| A_TimeIdlePhysical | Similar to above but ignores artificial keystrokes and/or mouse clicks whenever the corresponding hook (keyboard or mouse) is installed; that is, it responds only to physical events. (This prevents simulated keystrokes and mouse clicks from falsely indicating that a user is present.) If neither hook is installed, this variable is equivalent to A_TimeIdle. If only one hook is installed, only its type of physical input affects A_TimeIdlePhysical (the other/non-installed hook's input, both physical and artificial, has no effect). |
| A_TimeIdleKeyboard | If the keyboard hook is installed, this is the number of milliseconds that have elapsed since the system last received physical keyboard input. Otherwise, this variable is equivalent to A_TimeIdle. |
| A_TimeIdleMouse | If the mouse hook is installed, this is the number of milliseconds that have elapsed since the system last received physical mouse input. Otherwise, this variable is equivalent to A_TimeIdle. |
Hotkeys, Hotstrings, and Custom Menu Items
| A_ThisHotkey | The most recently executed hotkey or non-auto-replace hotstring (blank if none), e.g. #z. This value will change if the current thread is interrupted by another hotkey, so be sure to copy it into another variable immediately if you need the original value for later use in a subroutine. When a hotkey is first created -- either by the Hotkey function or a double-colon label in the script -- its key name and the ordering of its modifier symbols becomes the permanent name of that hotkey, shared by all variants of the hotkey. See also: A_ThisLabel |
| A_PriorHotkey | Same as above except for the previous hotkey. It will be blank if none. |
| A_PriorKey | The name of the last key which was pressed prior to the most recent key-press or key-release, or blank if no applicable key-press can be found in the key history. All input generated by AutoHotkey scripts is excluded. For this variable to be of use, the keyboard or mouse hook must be installed and key history must be enabled. |
| A_TimeSinceThisHotkey | The number of milliseconds that have elapsed since A_ThisHotkey was pressed. It will be -1 whenever A_ThisHotkey is blank. |
| A_TimeSincePriorHotkey | The number of milliseconds that have elapsed since A_PriorHotkey was pressed. It will be -1 whenever A_PriorHotkey is blank. |
| A_EndChar | The ending character that was pressed by the user to trigger the most recent non-auto-replace hotstring. If no ending character was required (due to the * option), this variable will be blank. |
Operating System and User Info
| A_ComSpec | Contains the same string as the environment's ComSpec variable (e.g. C:\Windows\system32\cmd.exe). Often used with Run/RunWait. |
| A_Temp | The full path and name of the folder designated to hold temporary files (e.g. C:\DOCUME~1\<UserName>\LOCALS~1\Temp). It is retrieved from one of the following locations (in order): 1) the environment variables TMP, TEMP, or USERPROFILE; 2) the Windows directory. |
| A_OSVersion |
The version number of the operating system, in the format "major.minor.build". For example, Windows 7 SP1 is 6.1.7601. Applying compatibility settings in the AutoHotkey executable or compiled script's properties causes the OS to report a different version number, which is reflected by A_OSVersion. |
| A_Is64bitOS | Contains 1 (true) if the OS is 64-bit or 0 (false) if it is 32-bit. |
| A_PtrSize | Contains the size of a pointer, in bytes. This is either 4 (32-bit) or 8 (64-bit), depending on what type of executable (EXE) is running the script. |
| A_Language | The system's default language, which is one of these 4-digit codes. |
| A_ComputerName | The name of the computer as seen on the network. |
| A_UserName | The logon name of the user who launched this script. |
| A_WinDir | The Windows directory. For example: C:\Windows |
| A_ProgramFiles |
The Program Files directory (e.g. On 64-bit systems (and not 32-bit systems), the following applies:
|
| A_AppData | The full path and name of the folder containing the current user's application-specific data. For example: C:\Documents and Settings\Username\Application Data |
| A_AppDataCommon | The full path and name of the folder containing the all-users application-specific data. |
| A_Desktop | The full path and name of the folder containing the current user's desktop files. |
| A_DesktopCommon | The full path and name of the folder containing the all-users desktop files. |
| A_StartMenu | The full path and name of the current user's Start Menu folder. |
| A_StartMenuCommon | The full path and name of the all-users Start Menu folder. |
| A_Programs | The full path and name of the Programs folder in the current user's Start Menu. |
| A_ProgramsCommon | The full path and name of the Programs folder in the all-users Start Menu. |
| A_Startup | The full path and name of the Startup folder in the current user's Start Menu. |
| A_StartupCommon | The full path and name of the Startup folder in the all-users Start Menu. |
| A_MyDocuments | The full path and name of the current user's "My Documents" folder. Unlike most of the similar variables, if the folder is the root of a drive, the final backslash is not included. For example, it would contain M: rather than M:\ |
| A_IsAdmin | If the current user has admin rights, this variable contains 1. Otherwise, it contains 0. To have the script restart itself as admin (or show a prompt to the user requesting admin), use Run *RunAs. However, note that running the script as admin causes all programs launched by the script to also run as admin. For a possible alternative, see the FAQ. |
A_ScreenWidth |
The width and height of the primary monitor, in pixels (e.g. 1024 and 768). To discover the dimensions of other monitors in a multi-monitor system, use SysGet. To instead discover the width and height of the entire desktop (even if it spans multiple monitors), use the following example: VirtualWidth := SysGet(78) VirtualHeight := SysGet(79) In addition, use SysGet to discover the work area of a monitor, which can be smaller than the monitor's total area because the taskbar and other registered desktop toolbars are excluded. |
| A_ScreenDPI | Number of pixels per logical inch along the screen width. In a system with multiple display monitors, this value is the same for all monitors. On most systems this is 96; it depends on the system's text size (DPI) setting. See also the GUI's -DPIScale option. |
| A_IPAddress1 through 4 | The IP addresses of the first 4 network adapters in the computer. |
Misc.
| A_Cursor | The type of mouse cursor currently being displayed. It will be one of the following words: AppStarting, Arrow, Cross, Help, IBeam, Icon, No, Size, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, UpArrow, Wait, Unknown. The acronyms used with the size-type cursors are compass directions, e.g. NESW = NorthEast+SouthWest. The hand-shaped cursors (pointing and grabbing) are classified as Unknown. |
| A_EventInfo | Contains additional information about the following events:
Note: Unlike variables such as A_ThisHotkey, each thread retains its own value for A_EventInfo. Therefore, if a thread is interrupted by another, upon being resumed it will still see its original/correct values in these variables. Read/write: A_EventInfo can also be set by the script, but can only accept unsigned integers within the range available to pointers (32-bit or 64-bit depending on the version of AutoHotkey). |
| Clipboard | Read/write: The contents of the OS's clipboard, which can be read or written to. See the Clipboard section. |
| ClipboardAll | Read-only: The entire contents of the clipboard (such as formatting and text). See ClipboardAll. |
| ErrorLevel | Read/write: See ErrorLevel. |
| A_LastError | Read/write: This is usually the result from the OS's GetLastError() function after the script calls certain functions, or the HRESULT of the last COM object invocation. See DllCall or Run/RunWait for more details. Assigning a value to A_LastError also causes the OS's SetLastError() function to be called. |
Loop
| A_Index | Read/write: This is the number of the current loop iteration (a 64-bit integer). For example, the first time the script executes the body of a loop, this variable will contain the number 1. For details see Loop or While-loop. |
| A_LoopFileName, etc. | This and other related variables are valid only inside a file-loop. |
| A_LoopRegName, etc. | This and other related variables are valid only inside a registry-loop. |
| A_LoopReadLine | See file-reading loop. |
| A_LoopField | See parsing loop. |
Variable Capacity and Memory
- When a variable is given a new string longer than its current contents, additional system memory is allocated automatically.
- The memory occupied by a large variable can be freed by setting it equal to nothing, e.g.
var := "". - There is no limit to how many variables a script may create. The program is designed to support at least several million variables without a significant drop in performance.
- Functions and expressions that accept numeric inputs generally support 15 digits of precision for floating point values. For integers, 64-bit signed values are supported, which range from -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF). Any integer constants outside this range are truncated. Similarly, arithmetic operations on integers wrap around upon overflow (e.g. 0x7FFFFFFFFFFFFFFF + 1 = -0x8000000000000000).