Dynamic Variables
General Conventions
Names: Різноманітні і функції Name не є випадку-sensitive (для прикладу, CurrentDate is the same as currentdate ). Для того, щоб розмістити таке як максимальне число і можливі характеристики, віртуальний Names.
No typed variables: Variables have no explicitly defined type; instead, якість будь-якого типу може бути встановлена в будь-якій variable (за винятком constants and built-in variables). Номери можуть бути автоматично поєднані до strings (text) і vice versa, depending on situation.
Declarations are optional: За винятком, коли помічено на функціях сторінки, параметри не потребуються. However, досліджуючи read a variable, тому що це ведеться за значенням, що розглядається як помилка.
Spaces are mostly ignored: Indentation (leading space) є важливим для написання readable code, але не вимагається за програмою і є в цілому ignored. Spaces and tabs are generally ignored at end of a line and within an expression (except between quotes). However, spaces є важливим у деяких випадках, включаючи:
- Function and method calls require the be to space between the function/method name and ( .
- Spaces є необхідним при розробці конфіденційності.
- Spaces можуть бути потрібні між двома операторами, щоб звільнити ambiguity.
- Single-line comments require leading space if they not at the start of the line.
Line breaks are meaningful: Line breaks зазвичай act as statement separator, terminating the previous function call or other statement. (A statement is simply the smallest standalone element of language that expreses some action to be carried out.) Exception to this is line continuation (see below).
Line continuation: Long lines може бути divided up в колекції дрібних ones для підвищення readability і maintainability. Це використовується для попереднього процесу, так що не є частиною мови як така. There are three methods:
- Continuation prefix: Лінії, які з'являються під час з'ясування оператора (except ++ and --) є merged with the previous line. Lines є merged regardless of whether line фактично contains an expression.
- Continuation by enclosure: A sub-expression enclosed in (), [] or <> може автоматично span multiple lines в most cases.
- Continuation section: Multiple lines є merged with the line above the section, which starts with ( and ends with ) (both symbols must appear at the beginning of a line, excluding whitespace).
Comments
Comments є порції тексту ззаписом, які були ignored program. Вони є типово використані для розширення або заборонених частин коду.
Scripts can be commented by using a semicolon at the beginning of a line. For example:
; This entire line is a comment.
Коментарі можуть також бути приєднані до кінця лінії, в яких випадку semicolon повинен мати на одному місці або tab до його лівого. For example:
Run "Notepad" ; Це є коментар на тій самій лінії як функція call.
In addition, the /* and */ symbols can be used to comment out entire section, as in this example:
/* MsgBox "This line is commented out (disabled)." MsgBox "Common mistake:" */ " this does not end the comment." MsgBox "This line is commented out." */ MsgBox "Ця line не має коментарів." /* Це є також valid, але не інший код може share the line. */ MsgBox "Ця line не має коментарів."
Excluding tabs and spaces, /* must appear at the start of the line, while */ може з'явитися тільки при запуску або кінці з лінії. It is also valid to omit */ , в якому випадку основа файлу є зареєстрованою.
Незабаром коментарі filtred out when the script read from file, they do not impact performance or memory utilization.
Expressions
Expressions є комбінаціями одного або більше цін, варіантів, операторів і функцій calls. Для прикладу, 10 , 1+1 і MyVar є дійсними expressions.Зазвичай, expression таке один або більше значення, як введення, виконання однієї або більше операцій, а також виробляє значення як результат. Процеси finding out the value of an expresion is called evaluation. Для прикладу, зображення 1+1 evaluates до числа 2.
Додаткові вирази можуть бути зроблені для того, щоб формувати більш широкі комплексні вирази. Для прикладу, якщо обліковий запис/100 перетворюється на відсотковий відсоток на фракцію, 1 - дисконт/100 обчислює фракцію, спрямовану на заміну об'єму, і ціни * (1 - відсоток/100) applies it to produce net price.
Values є номери, об'єкти або strings. A literal value is one written physically in the script; one that you can see when you look at the code.
Strings / Text
Для більш загальної explanation of strings, see Strings.
A string, or string of characters, is just a text value. Під час дзвінка, літеральний текст повинен бути включений в один або два quotation marks до різниці його з варіативним ім'ям або деяким іншим виразом. This is often referred to as a quoted literal string, or just quoted string. Для прикладу, "this is a quoted string" and 'so is this' .
To include an actual quote character inside a quoted string, use the `` or `' escape sequence or enclose the character in opposite type of quote mark.
Quoted strings може полягати в інших escape sequences such as `t (tab), `n (linefeed), and `r (carriage return).
Variables
Для основних explanation і загальних details про variables, viz Variables.
Variables can be used in an expression simply by writing the variable's name. Для прикладу, A_ScreenWidth/2 . Хоча, параметри можуть бути використані в quoted string. Instead, variables та інші значення можуть бути з'єднані з текстом через процеси названі concatenation. There are two ways to concatenate values in an expression:
- Implicit concatenation: "The value is " MyVar
- Висловлює констатацію: "The value is". MyVar
Implicit concatenation is also known as auto-concat. У звичайних випадках, територіях, що беруть участь в variable і dot є mandatory.
Формат функції може бути використаний для цього purpose. For example:
MsgBox Формат("Ви використовуєте AutoHotkey v -bit.", A_AhkVersion, A_PtrSize*8)
Щоб відобразити значення до variable, використовуйте := assignment operator, as in MyVar := "Some text" .
Percent signs within an expression є використаний для створення dynamickих variable references, але вони є rarel needed.
Keyword Constants
A constant is simply an unchangeable value, given a symbolic name. AutoHotkey currently has following constants:
| Name | Value | Type | Description |
| False | 0 | Integer | Boolean false, sometimes meaning "off", "no", etc. |
| True | 1 | Integer | Boolean true, sometimes meaning "on", "yes", etc. |
Недозволяє read-only bud-in variables, вони не можуть бути відновлені за динамічною повідомлень.
Operators
Operators Виберіть форму символу або групу символів так як + або : = , або один з слів і , або , не , є , або contains . Вони мають одну, дві або три значення, як вхід і відновити значення як результат. Якість або sub-expression використовуваний як вхід для оператора є названий an operand.
- Unary Оператори написують їх перед або після одного оператора, залежно від оператора. Для прикладу, -x або no keyIsDown .
- Binary operadors є written в між своїми 2 operands. Для прикладу, 1+1 або 2 * 5 .
- AutoHotkey has only one ternary operator, which takes the form condition ? valueIfTrue: valueIfFalse.
Кілька бездітних і binary operadors share the same symbols, в яких випадку з'ясувати, що operador depends on whether it is written before, after or in between two values. Для прикладу, x-y параметри subtraction while -x inverts sign of x (виробляючи позитивну ціну від negative value and vice versa).
Operators ecual precedence така як multiply ( * ) і divide ( / ) є встановлена в лівій-на-праві ордер без назви іншихвикладів, що знаходяться в операційному table. Як contrast, operador operator of low precedence так як add ( + ) є встановлений після того, як один такий як multiply ( * ). Для прикладу, 3 + 2 * 2 є оцінюється як 3 + (2 * 2) . Parentheses може бути використаний для override precedence as in this example: (3 + 2) * 2
Function Calls
Для загальної explanation of functions and related terminology, see Functions.
Functions така варіація номера вхідних повідомлень, perform some action or calculation, and then return a result. The inputs of a function are called parameters or arguments. A function is called simply by writing the target function спливає з параметрами, встановленими в parentheses. Для прикладу, GetKeyState("Shift") відновлює (відображається до) 1 Якщо Shift є неповним або 0 іншимwise.
Note: Вони не повинні бути будь-яким простір між функцією і Open parenthesis.
Для того, щоб новим програмуванням, требуванням для parentheses може seem cryptic or verbose at first, but they are what allows a function call to be combined with other operations. Для прикладу, підтримка GetKeyState("Shift", "P") і GetKeyState("Ctrl", "P") відобразить 1 тільки якщо key keys є фізично встановлені.
Although a function call expression зазвичай починають з literal function name, target of call can be any expression which produces a function object. In the expression GetKeyState("Shift") , GetKeyState is actually a variable reference, although it usually refers to a read-only variable containing a built-in function.
Function Call Statements
Якщо зміна значення функції не потребує і функція name є написана на запуску лінії (або в інших контекстах, які можуть бути зроблені, так само, як і в цьому або hotkey), parentheses може бути заміщений. У цьому випадку, залишок лінії є такою як функція параметра list. For example:
result := MsgBox("Цей один потребує parentheses.",, "OKCancel") MsgBox "Цей один не потребує."
Спосіб може також бути заміщений, коли беручи метод в цьому самому контексті, але тільки коли target об'єкта є її variable або безпосередньо наміченою особливістю, так як myVar.myMethod or myVar.myProp.myMethod .
Як з функцією call expressions, target of function call statement does no have to be a predefined function; it can instead be a variable containing a function object.
A функція call statement can span multiple lines.
Function call statements має наступні обмеження:
- If there is a return value, it is always discarded.
- Як control flow statements, вони можутьне використовуватися всередині expression.
- Якщо опційні parametrи є заміщені, будь-який commas at the end з параметра list повинен бути заміщений до попередньої лінії запуску.
- Функція call statements не може бути variadic, однак вони можуть пройти fixed number parameters to a variadic function.
Optional Parameters
Опційні параметри можуть бути невеликими бланк, але делімітивна комма залишається необхідним для всіх незмінних параметрів, а також заміщених. Для прикладу, Run функція може бути прийнята між одним і чотирма параметрами. Все з наступних valid:
Run "notepad.exe", "C:\" Run "notepad.exe",, "Min" Run("notepad.exe", , , ¬epadPID)
З функцією call, array literal or object literal, keyword unset can be used to explicitly omit the parameter or value. На unset expression has one of the following effects:
- Для user-defined function, значення параметра default value is used.
- Для будови в функцію, цей параметр вивчається, щоб бутизроблено.
- Для array literal such as [var?] , елемент included в array's length but is given no value.
- Для об'єкта literal such as , the property is not assigned.
Unset keyword може також бути використана в функцію визначення до того, що параметр є опційним, але не є меншим значенням.Коли функція виконується, місцеві параметри відповідають тому, що параметр буде не значення, якщо параметр був заміщений.
The maybe operator (var?) може бути використаний для pass or omit variable depending on whether it has a value. Для прикладу, Array(MyVar?) є подібним до Array(IsSet(MyVar) ? MyVar : unset) .
Operators for Objects
Там є інші символи, що використовуються в текстах, які не можуть бути використані в будь-який час з категорії, визначені вище, або, що впливає на зміну інших частин експозиції, як описано нижче. The all relate to objects in some way. Проводячи повне розповсюдження того, що всі конструктиви можуть бути введені більше концепцій, які є поза межами цього розділу.
Alpha.Beta is often called member access. Alpha is ordinary variable, і може бути переміщена з функцією call або деякою іншою sub-expression which returns an object. Якщо виявлено, що object is sent a request "відповідь мені є значенням property Beta", "store this value in property Beta" or "call the method named Beta". In other words, Beta is a name which has meaning to the object; it is not a local або global variable.
Alpha.Beta() is a метод call, як описано над. parentheses can be omitted in specific cases; see Function Call Statements.
Alpha.Beta[Param] є специфічною формою member access which includes additional parameters in the request. While Beta is a simple name, Param is ordinary variable або sub-expression, або list of sub-expressions separated by commas (same as in a function's parameter list). Variadic calls є permitted.
Alpha.%vBeta% , Alpha.%vBeta%[Param] and Alpha.%vBeta%() are also member access, but vBeta is a variable або sub-expression. Це дозволяє назву імені або методу, щоб визначити, коли script is running. Parentheses є необхідним, коли calling a method this way.
Alpha[Index] accesses the default property of Alpha , giving Index as a parametr.Both Alpha and Index є варіації в цьому випадку, і може бути переміщений з віртуальною будь-якою sub-expression. Цей syntax використовується, як правило, повторюваний елемент елемента Array or Map.
[A, B, C] створюють array with initial contents A, B and C (all variables in this case), де A is element 1.
creates an Object with properties literally named Prop1 and Prop2. A value can later be retrieved by using the member access syntax описано над. Для оцінки property name as an expression, enclose it in percent signs. Для прикладу: .
MyFunc(Params*) is a variadic function call. Asterisk must immediately precede closing parenthesis наприкінці функції параметра list. Params повинен бути variable або sub-expression, які відображають на Array або інші номерні об'єкти. Але це неправильно, щоб використовувати Params* тільки в будь-якому випадку, він може бути використаний в array literal ( [A, B, C, ArrayToAppend*] ) або property parameter list ( Alpha.Beta[Params*] or Alpha[Params* ]).
Expression Statements
Не всі зображення можуть бути використані тільки на лінії. Для прикладу, на лінію, що складається з 21 * 2 або "Котрий текст", не може бути any sense. An expression statement is expression used on its own, типово для його side-effects. Більшість повідомлень з side-effects може бути використана в цьому способі, тому що це не обов'язково необхідна до пам'яті деталей цієї секції.
Наступні типи expressions можуть бути використані як:
Assignments, as in x := y , compound assignments such as x += y , і increment/decrement operators such as ++x and x-- .
Known limitation: Для x++ і x-- , є поточно може бутинеобов'язково між межами variable name and operator.
Function calls such as MyFunc(Params) . However, standalone функція call cannot може бути спрямований до Open Brace < (на кінці кінця або на next line), тому що він повинен бути confused with function declaration.
Method calls such as MyObj.MyMethod() .
Member access using square brackets, так як MyObj[Index] , які можуть мати side-effects як function call.
Ternary expressions such as x ? CallIfTrue() : CallIfFalse() . However, it is safer to utilize the rule below; that is, always enclose the expression (або just the condition) в parentheses.
Known limitation: Сприяє ambiguity з функцією call statements, умовами починання з варіативним name і space (але полягають інші оператори) повинні бути включені в parentheses. Для прикладу, (x + 1) ? y: z and x+1? y : z are expression statements but x + 1 ? y : z is a функція call statement.
Note: Condition cannot begin with ! або будь-який інший Expression Operator, як він повинен бути interpreted як continuation line.
Expressions starting with ( . However, вони зазвичай повинні бути виконані ) на саму лінію, іншіwise the line would be interpreted as start of a continuation section.
Expressions starting with double-deref, так само як %varname% := 1 . Це є в першу чергу для здійснення комплексності.
Expressions що start with any of those described above (but not those described below) are also allowed, for simplicity. Для прикладу, MyFunc()+1 є поточно дозволеним, алеякщо +1 не має ніякого ефекту і його результат є висловленим. Такі expressions можуть бути invalid in future due до покращеного error-checking.
Функція call statements є аналогічною до expression statements, але є technically not pure expressions. Для прикладу, MsgBox "Hello, world!" , myGui.Show or x.y.z "my parameter" .
Control Flow Statements
Для загального розширення контрольного потоку, бачте Control Flow.
Statements є grouped together into a block при натисканні на них в braces <> , як в C, JavaScript і подібні мови, але зазвичай braces повинні appear at the start of a line. Control flow statements може бути застосований до entire block або just a single statement.
The body of control flow statement is always a single group of statements.У блоці Counts є єдиною групою статей, як керувати потоком статей і його body. Протягом наступних статей є також grouped with each other, along with their bodys: If with Else ; Loop / For with Until or Else; Try with Catch and/or Else and/or Finally . У інших словах, коли група цих статей є використана як усі, вона не може бути потрібна, щоб бути внесена в braces (however, some coding styles always include the braces, for clarity).
Control flow statements which have body and therefore must always be followed by related statement or group of statements: If , Else , Loop , While , For , Try , Catch and Finally .
The following control flow statements exist:
- A block (denoted by a pair of braces) групи zero або more statements to act as a single statement.
- Якщо вони становлять відповіді його тіла, щоб бути виконаним або не depending on a condition. Це може бути спричинене Else statement, який виконується тільки якщо умова була не met.
- Goto jumps до конкретних повідомлень і continues execution.
- Return returns від функції.
- A Loop statement (Loop, While or For) виконує його body repeatedly.
- Break exits (terminates) a loop.
- Конфіденційні скипи залишку поточної промені ітерації і початку нової однієї.
- Until causas a loop to terminate when an expression evaluates to true. The expression is evaluated after each iteration.
- Try guards його тіло до нагальних errors and values thrown by the throw statement.
- Catch executes if exception of given typ is thrown within try statement.
- Else, коли використовується після catch statement, executes тільки якщо не виключення є thrown within try statement.
- Finale executes його тіла, коли керування є переведений з try або catch statement's body.
- Запустіть, щоб виключити, щоб було спричинено спробою/використовувати або наError, або натиснути на error dialog.
Control Flow vs. Інші Statements
Control flow statements differ from function call statements in several ways:
- Отримуючи браму блоку може бути написано на кінці тієї ж лінії як If, Else, Loop, While, For, Try, Catch or Finally statement (базично будь-який control flow statement which has body). Це referred to as One True Brace (OTB) style.
- Else, Try і Final allow any valid statement to their right, as they require a body but have no parameters.
- If, While, Return, Until, Loop Count, For, Catch, Break, Continue, Throw, і Goto дозволяє відкритий parenthesis, щоб бути застосований одразу після назви, до назви пункту позначки. Although these look like function calls, вони не є, і неможна використовувати mid-expression. For example, if(expression) .
- Control flow statements cannot be overridden by Definition a function with the same name.
Loop Statement
Існують кілька типів променевих станів:
- Loop Count executes a statement repeatedly: either the specified number of times or until Break is encountered.
- Loop Reg retrieves the contents of specified registry subkey, один пункт у часі.
- Loop Files retrieves the specified files or folders, one at a time.
- Loop Parse retrieves substrings (fields) від string, one at a time.
- Loop Read retrieves lines в текстовому файлі, один при часі.
- Коли executes a statement repeatedly until the specified expression evaluates to false. The expression is evaluated before each iteration.
- Для executes statement once for each value or pair of values returned by enumerator, su as each key-value pair in an object.
Break exits (terminates) a loop, ефективно jumping до next line after the loop's body.
Конфіденційні скипи залишку поточної промені ітерації і початку нової однієї.
Until causas a loop to terminate when an expression evaluates to true. The expression is evaluated after each iteration.
Розмітка може бути використана для "назви" для пропозиції Continue and Break. Це дозволяє script до легкого призначення або переміщатися з будь-якого номера невдалих провалів без використання Goto.
The built-in variable A_Index contains the number of the current loop iteration. Це contains 1 перший час, щоб вилучити body є executed. For the second time, it contains 2; and so on. Якщо внутрішнє проміжок є встановленим за власним вухом, у внутрішній промені виявляється послідовність. A_Index робіт всередині всіх типів проривів, але містять 0 поза межами променів.
Для деяких променевих типів, інші встановлені параметри, щоб переглянути інформацію про поточний випадок елемента (Registry key/value, file, substring or line of text). Ці variables have names beginning with A_Loop, such as A_LoopFileName and A_LoopReadLine. Їх значення завжди відповідають mostу, який раніше переміщено (але не може бути схильнено) випадок відповідного типу. Для прикладу, A_LoopField returns поточний substring в внутрішній повторюваному прориві, навіть якщо він використовується всередині файлу або заголовку прориву.
- Функція може бути названа script itself. Цей малюнок функції може бути використаний для будь-якого відхилення, щоб зробити код більше manageable, або застосовується до інших purposes.
- Функція може бути названа програмою в відповідь на деякий час, так як user pressing a hotkey. Для того, щоб кожен hotkey is asocied with function to execute whenever hotkey is pressed.
#w::Run "wordpad" ; Press Win-W to run Wordpad. #n:: ; Press Win-N to run Notepad.
SetTimer() => MsgBox("Hello!"), -1000 ; Says hello after 1 second.
SayHello() => MsgBox("Hello!")
Різноманітність у функціях є місцевість для того, щоб функція зазнала, except in the following cases:
- Коли функція є assume-global.
- Якщо variable is referenced but not used as the target of an assignment or the reference operator ( &var ).
- Якщо мова йде про місцеву функцію outer функцій всередині незмінної функції.
A функція може бути optionally accept parameters. Parameters are defined by listing them inside the parentheses. For example:
MyFunction(FirstParameter, Second, &Third, Fourth:="") < ;. return "a value" >
Як з функцією calls, вони повинні бути недоступні між функцією name і Open-parenthesis.
Line break between the close-parenthesis and open-brace is optional. Вони можуть бути будь-якою ціною whitespace або коментарі між двома.
The ByRef marker (&) позначається, що Caller повинен пройти pass a variable reference. Всередині функції, any reference to the parameter will actually access the caller's variable. Це є подібним до відхилення & і explicitly dereferencing the parameter inside the function (e.g. %Third% ), але в цьому випадку процентні signs є omitted. Якщо параметр є опційним і електронним omits it, параметр acts as normal local variable.
Optional parameters є specified by following the parameter name with := and default value, which must be literal quoted string, number, true , false or unset .
Функція може відновити значення. Якщо це не означає, що більша кількість оборотів є empty string.
Функція визначення не потрібна для того, щоб змінити курси на те, що функція.
See Functions for much more detail.
#Include
#Include directive causas script до behave as though the specified file's contents are present at this exact position. Це використовується для організації коду в окремі файли, або для використання script libraries написані за іншими користувачами.
У #Include file може бути отриманий загальний код для виконання script startup, але як з кодом в головному файлі script, так і код, який буде виконано тільки якщо auto-execute thread не є виконаним (такий як з unconditional Return ) prior to the #Include directive. Warning is displayed by default if any code cannot be executed due to a prior Return .
Невідповідно до C/C++, #Include does nothing if the file is already been included by a previous directive. Увімкнути вмісту самого файлу кілька разів, використовуючи #IncludeAgain.
Для того, щоб використовувати графічні scripts, #Include can search a few standard locations for library script. For details, viz Script Library Folders.
Miscellaneous
Dynamic Variables
A dynamic variable reference так, як текст значення і interpretas це як назва variable.
Note: be variable cannot be created за динамічний реference, але існуючі параметри можуть бути визначені. Це включає всі параметри, які підписують нединамічні посилання на те, що вони не будуть визначені значення.
The most common form of dynamic variable reference is called a double reference or double-deref. Перед виконанням двосторонньої сторінки, назва target variable is stored in a second variable. Ця секунда variable може бути використана до величини значення до параметра параметра вdirectly, використовуючи double reference. For example:
target := 42 second := "target" MsgBox second ; Normal (single) variable reference => target MsgBox %second% ; Double-deref => 42
Currently, second must always contain a variable name in the second case; arbitrary expressions не підтримується.
Як динамічна варіаційна інформація може бути один або більше частин літературного тексту і вміст одного або більше варіацій, і вводити їх до форми для однієї variable name. Це означає, що необхідно записати сторінки іконки і послідовності, що містяться в послідовності, без будь-яких місць. Для прикладу, MyArray%A_Index% або MyGrid%X%_%Y% . This is used to access pseudo-arrays, описані нижче.
Ці технології можуть бути застосовані до властивостей і методів об'єктів. For example:
clr := <> for n, component in ["red", "green", "blue"] clr.%component% := Random(0, 255) MsgBox clr.red "," clr.green "," clr .blue
Pseudo-arrays
A pseudo-array is actually just a banda discrete variables, but with naming pattern which allows them to be used like elements of an array. For example:
MyArray1 := "A" MyArray2 := "B" MyArray3 := "C" Loop 3 MsgBox MyArray%A_Index% ; Shows A, then B, then C.
"index" використовується для форми кінцевої версії name не має значення; it could instead be a letter or keyword.
Для цих умов, це є в основному пристосований до використання на Array or Map instead of pseudo-array:
- Як окремі елементи є just normal variables, один може assign or retrieve a value, але cannot remove or insert елементів.
- Тому, що pseudo-array є тільки conceptual і не має значення, він може бути пройдений або відхилений від функції, або зроблений як цілий.
- A pseudo-array не може бути визначено як усі, так і деякі "елементи" можуть відповідати на глобальні (або зображені) варіації, коли інші не.
- Якщо варіативна мова не відповідає динамічно, але тільки визначена динамічно, load-time warning може бути displayed. Такі варіації є дуже ефективним способом для виявлення помилок, тому що невідповідно їм не recommended.
- Сучасні версії англійської мови не можуть створювати нові параметри динамічно. Це є partly to encourage best practices, і partly to avoid inconsistency між dynamic і non-dynamic variable references in functions.
Labels
Натисніть на лінію коду, і може бути використана як Goto target або для конкретної прориву до розриву з або до кінця. A label consist of a name followed by a colon:
Зовнішньо від whitespace і коментарі, не інший код може бути написаний на саму лінію як мітку. For more details, more Labels.