-
irenestjude
- Posts: 3
- Joined: 03 Jun 2021, 19:56
Error: Return’s parameter should be blank except inside a function
Hi! I keep getting the error message
- Error2.png (30.96 KiB) Viewed 789 times
Here is my script:
Code: Select all
!-::
Send,—
Return
!>::
Send,→
Return
!<::
Send,←
Return
!6::
Send,↑
Return
!d::
Send,↓
Return
!=::
Send,±
Return
!c::
Send,∆
Return
!n::
Send,≠
Return
!`
Send,≈
Return
^&!,
Send,≤
Return
^&!
Send,≥
Return
Basically, my new laptop doesn’t have a number pad so I can’t use alt-codes for special characters. So I am using this app to create hotkeys for my most used characters.
Thanks for your help.
-
irenestjude
- Posts: 3
- Joined: 03 Jun 2021, 19:56
Re: Error: Return’s parameter should be blank except inside a function
04 Jun 2021, 11:00
mikeyww wrote: ↑
03 Jun 2021, 21:11
What are you attempting in the last three hotkeys, where you drop ::?See: Prefix keys
Thanks for pointing that out. I’ve fixed it:
Code: Select all
!-::
Send,—
Return
!>::
Send,→
Return
!<::
Send,←
Return
!6::
Send,↑
Return
!d::
Send,↓
Return
!=::
Send,±
Return
!c::
Send,∆
Return
!n::
Send,≠
Return
!`::
Send,≈
Return
^&!,::
Send,≤
Return
^&!.::
Send,≥
Return
Now I’m getting the error message:
- Error.png (14.83 KiB) Viewed 755 times
-
swagfag
- Posts: 5799
- Joined: 11 Jan 2017, 17:59
Re: Error: Return’s parameter should be blank except inside a function
04 Jun 2021, 12:54
^ is the modifier shorthand for Ctrl, which requires being (ultimately) paired with a non-shorthand hotkey
Ctrl + Alt + , should have been ^!,::, not ^&!,::(which indeed is an invalid hotkey)
-
irenestjude
- Posts: 3
- Joined: 03 Jun 2021, 19:56
Re: Error: Return’s parameter should be blank except inside a function
04 Jun 2021, 13:53
swagfag wrote: ↑
04 Jun 2021, 12:54
^ is the modifier shorthand for Ctrl, which requires being (ultimately) paired with a non-shorthand hotkey
Ctrl + Alt + , should have been ^!,::, not ^&!,::(which indeed is an invalid hotkey)
You are the GOAT. Thank you!
Return to “Ask for Help”
|
Authenticator Code |
|
Thread Tools |
Head only aimbot overwatch 2 |
|
#1 |
|||||||||||
Sunoki Member Join Date: Apr 2022
Reputation: 103 Points: 3,082, Level: 5 Level up: 36%, 518 Points needed Activity: 5.4% Last Achievements |
I made a ahk head only aimbot for overwatch 2 this works with red outlines. Edit: because you guys are calling me a troll this is a video of me using it you need to change the settings for your dpi and sens video: https://streamable.com/7fcnqe to fix the aimbot change MoveX * 0.80 and MoveY * 0.80. if you have a low sens turn it up by 0.10 and if you have a high sens put it lower by 0.10 if 0.10 is still too fast change the number to 1 / 2 or more only change the right number than change the move number higher or lower Code: #Persistent #KeyHistory, 0 #NoEnv #HotKeyInterval 1 #MaxHotkeysPerInterval 127 #InstallKeybdHook #UseHook #SingleInstance, Force SetKeyDelay,-1, 8 SetControlDelay, -1 SetMouseDelay, -1 SetWinDelay,-1 SendMode, InputThenPlay SetBatchLines,-1 ListLines, Off CoordMode, Pixel, Screen, RGB CoordMode, Mouse, Screen PID := DllCall("GetCurrentProcessId") Process, Priority, %PID%, High EMCol := " 0xab0001, 0xb7394f, 0xb93742, 0xbb3340, 0xca4c5a, 0xbf3f4c, 0xd0262e, 0xd1262e, 0xd22830, 0xb0535f, 0xd1272e " ColVn := 20 //dont change ZeroX := 960 //dont change ZeroY := 540 //dont change CFovX := 20 //dont change CFovY := 20 //dont change ScanL := ZeroX - 40 //fov ScanR := ZeroX + 40 //fov ScanT := ZeroY - 40 //fov ScanB := ZeroY + 40 //fov Loop, { ~XButton2:: Start := A_TickCount while GetKeyState("XButton2") && A_TickCount - Start < 600000 { PixelSearch, AimPixelX, AimPixelY, ScanL, ScanT, ScanR, ScanB, EMCol, ColVn, Fast RGB GoSub GetAimOffset GoSub GetAimMoves GoSub MouseMoves } GetAimOffset: AimX := AimPixelX - ZeroX AimY := AimPixelY - ZeroY AimY := AimPixelY+1 - ZeroY If ( AimX > 0 ) { DirX := 1 } If ( AimX < 0 ) { DirX := -1 } If ( AimY > 0 ) { DirY := 1 } If ( AimY < 0 ) { DirY := -1 } AimOffsetX := AimX * DirX AimOffsetY := AimY * DirY Return GetAimMoves: RootX := Ceil(( AimOffsetX ** ( 1 / 1 ))) RootY := Ceil(( AimOffsetY ** ( 1 / 1 ))) MoveX := RootX * DirX MoveY := RootY * DirY ;same here Return //you can change the speed up or down for more or less locky aimbot works best on widowmaker and i need to add more colors so it works farther away MouseMoves: DllCall("mouse_event", uint, 1 , int, MoveX * 1.40 , int, MoveY * 1.40 , uint, 0, int, 0) DllCall("Sleep", UInt, 0.02) //^speed //^speed return } return __________________
|
|||||||||||
Sunoki is offline |
|
#2 |
|||||||||||
loc83085 h4x0!2 Join Date: Aug 2019 Location: 🌏
Reputation: 537 Points: 3,389, Level: 5 Level up: 74%, 211 Points needed Activity: 1.8% Last Achievements |
Thanks for sharing! __________________ |
|||||||||||
loc83085 is online now |
|
#3 |
|||||||||||
Sunoki Member
Join Date: Apr 2022
Reputation: 103 Points: 3,082, Level: 5 Level up: 36%, 518 Points needed Activity: 5.4% Last Achievements |
Quote:
Originally Posted by loc83085 Thanks for sharing! No problem __________________ |
|||||||||||
Sunoki is offline |
|
#4 |
|||||||||||
B4nnyBun n00bie Join Date: Jan 2021
Reputation: 10 Points: 1,434, Level: 3 Level up: 5%, 666 Points needed Activity: 7.5% Last Achievements |
undetected? |
|||||||||||
B4nnyBun is offline |
|
#5 |
|||||||||||
Sunoki Member
Join Date: Apr 2022
Reputation: 103 Points: 3,082, Level: 5 Level up: 36%, 518 Points needed Activity: 5.4% Last Achievements |
Quote:
Originally Posted by B4nnyBun undetected? I cant tell you 100% but ive been using this from overwatch 1 — 2 so for me ive not gotten banned __________________ |
|||||||||||
Sunoki is offline |
|
#6 |
|||||||||||
Sens978 n00bie Join Date: May 2021
Reputation: 10 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
i keep getting error code |
|||||||||||
Sens978 is offline |
|
#7 |
|||||||||||
theknight428 n00bie Join Date: Mar 2021
Reputation: -21 Points: 1,281, Level: 2 Level up: 77%, 119 Points needed Activity: 2.8% Last Achievements |
i cant get it to work i keep getting an error saying returns parameter should be blank except inside a function for lines 67-78 |
|||||||||||
theknight428 is offline |
|
#8 |
|||||||||||
lnwmiloza007l n00bie Join Date: Nov 2020
Reputation: 10 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
not work |
|||||||||||
lnwmiloza007l is offline |
|
#9 |
|||||||||||
blackhair2 n00bie Join Date: Jun 2022
Reputation: 10 Points: 400, Level: 1 Level up: 45%, 500 Points needed Activity: 9.3% |
I think there’s something wrong. I am sorry about my English. I use a translator. |
|||||||||||
blackhair2 is offline |
|
#10 |
|||||||||||
Ssarkos Hacker Supreme Join Date: Oct 2020 Location: Germany
Reputation: 6596 Points: 11,732, Level: 13 Level up: 57%, 568 Points needed Activity: 29.8% Last Achievements |
This uses mouse_event which could get you banned. Just a heads up. |
|||||||||||
Ssarkos is online now |
|
#11 |
|||||||||||
libre1997 God-Like Join Date: Aug 2011
Reputation: 346 Points: 9,081, Level: 11 Level up: 35%, 719 Points needed Activity: 3.9% Last Achievements |
isn’t mouse events detected on OW? |
|||||||||||
libre1997 is offline |
|
#12 |
|||||||||||
Sunoki Member
Join Date: Apr 2022
Reputation: 103 Points: 3,082, Level: 5 Level up: 36%, 518 Points needed Activity: 5.4% Last Achievements |
ok ill tell you how to use and fix the code. 1. download auto hotkey they key is mouse button 5 you can change they key on line 38 and 40 you can find the key list at this link __________________
|
|||||||||||
Sunoki is offline |
|
#13 |
|||||||||||
XujanAbo Hacker Supreme Join Date: Jan 2020 Location: ARMENIA
Reputation: 415 Points: 3,685, Level: 6 Level up: 10%, 815 Points needed Activity: 3.9% Last Achievements |
OKAY i got the script to run, but it doesnt track anything am i doing something wrong? the outlines are red
|
|||||||||||
XujanAbo is offline |
|
#14 |
|||||||||||
Darkaim63 n00bie Join Date: May 2016
Reputation: 10 Points: 4,689, Level: 7 Level up: 21%, 711 Points needed Activity: 0% Last Achievements |
What do I change the fov values to if I use max FOV? |
|||||||||||
Darkaim63 is offline |
|
#15 |
|||||||||||
Nappyy n00bie Join Date: Aug 2020
Reputation: 10 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
Quote:
Originally Posted by Sunoki ok ill tell you how to use and fix the code. 1. download auto hotkey they key is mouse button 5 you can change they key on line 38 and 40 you can find the key list at this link You didn’t link the key list… |
|||||||||||
Nappyy is offline |
|
#16 |
|||||||||||
AgentCheatz n00bie Join Date: Apr 2022
Reputation: 10 Points: 350, Level: 1 Level up: 88%, 50 Points needed Activity: 0% |
Quote:
Originally Posted by XujanAbo OKAY i got the script to run, but it doesnt track anything am i doing something wrong? the outlines are red how did you get it to run in the first place? |
|||||||||||
AgentCheatz is offline |
|
#17 |
|||||||||||
flamedog22 n00bie Join Date: Apr 2018
Reputation: 10 Points: 3,407, Level: 5 Level up: 76%, 193 Points needed Activity: 9.7% Last Achievements |
Doesn’t work at all. Very spheritic movements if anything. |
|||||||||||
flamedog22 is offline |
|
#18 |
|||||||||||
josh7bernard n00bie Join Date: Aug 2021
Reputation: 10 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
after i remove words with // and make into a ahk file i keep getting target label does not exsist after trying to open the file Do you know the fix? |
|||||||||||
josh7bernard is offline |
|
#19 |
|||||||||||
rhwnsgh96 n00bie Join Date: Jul 2019
Reputation: 10 Points: 1, Level: 1 Level up: 0%, 1 Points needed Activity: 0% |
doesn’t work neither. can you post the code that we can just copy and paste? |
|||||||||||
rhwnsgh96 is offline |
|
#20 |
|||||||||||
LornJon5ID n00bie Join Date: Mar 2022
Reputation: 10 Points: 537, Level: 1 Level up: 28%, 363 Points needed Activity: 2.0% |
Quote:
Originally Posted by Sunoki I made a ahk head only aimbot for overwatch 2 this works with red outlines. Code: #Persistent #KeyHistory, 0 #NoEnv #HotKeyInterval 1 #MaxHotkeysPerInterval 127 #InstallKeybdHook #UseHook #SingleInstance, Force SetKeyDelay,-1, 8 SetControlDelay, -1 SetMouseDelay, -1 SetWinDelay,-1 SendMode, InputThenPlay SetBatchLines,-1 ListLines, Off CoordMode, Pixel, Screen, RGB CoordMode, Mouse, Screen PID := DllCall("GetCurrentProcessId") Process, Priority, %PID%, High EMCol := " 0xab0001, 0xb7394f, 0xb93742, 0xbb3340, 0xca4c5a, 0xbf3f4c, 0xd0262e, 0xd1262e, 0xd22830, 0xb0535f, 0xd1272e " ColVn := 20 //dont change ZeroX := 960 //dont change ZeroY := 540 //dont change CFovX := 20 //dont change CFovY := 20 //dont change ScanL := ZeroX - 40 //fov ScanR := ZeroX + 40 //fov ScanT := ZeroY - 40 //fov ScanB := ZeroY + 40 //fov Loop, { ~XButton2:: Start := A_TickCount while GetKeyState("XButton2") && A_TickCount - Start < 600000 { PixelSearch, AimPixelX, AimPixelY, ScanL, ScanT, ScanR, ScanB, EMCol, ColVn, Fast RGB GoSub GetAimOffset GoSub GetAimMoves GoSub MouseMoves } GetAimOffset: AimX := AimPixelX - ZeroX AimY := AimPixelY - ZeroY AimY := AimPixelY+1 - ZeroY If ( AimX > 0 ) { DirX := 1 } If ( AimX < 0 ) { DirX := -1 } If ( AimY > 0 ) { DirY := 1 } If ( AimY < 0 ) { DirY := -1 } AimOffsetX := AimX * DirX AimOffsetY := AimY * DirY Return GetAimMoves: RootX := Ceil(( AimOffsetX ** ( 1 / 1 ))) RootY := Ceil(( AimOffsetY ** ( 1 / 1 ))) MoveX := RootX * DirX MoveY := RootY * DirY ;same here Return //you can change the speed up or down for more or less locky aimbot works best on widowmaker and i need to add more colors so it works farther away MouseMoves: DllCall("mouse_event", uint, 1 , int, MoveX * 1.40 , int, MoveY * 1.40 , uint, 0, int, 0) DllCall("Sleep", UInt, 0.02) //^speed //^speed return } return Help error saying returns parameter should be blank except inside a function for lines 67-78 |
|||||||||||
LornJon5ID is offline |
|
Similar Threads |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
[Question] GA for head 2 head or scramble | boredom1234 | Grand Theft Auto V | 0 | 5th August 2021 10:14 PM |
Magic hit head even with no head shoot | Mut1234 | PUBG Mobile | 4 | 22nd June 2021 07:11 PM |
[Outdated] HOT{HEAD ONLY} COLOR AIMBOT+NORECOIL | arthure | Valorant | 173 | 22nd December 2020 02:04 AM |
[Question] Working head only pixel aimbot AHK | arthure | Valorant | 18 | 21st April 2020 06:26 PM |
Tags |
aimbot, overwatch, head, red, bar, [release], clips, health, aim, colors |
«
Previous Thread
|
Next Thread
»
Forum Jump |
All times are GMT. The time now is 03:13 PM.
Contact Us —
Toggle Dark Theme
Terms of Use Information Privacy Policy Information
Copyright ©2000-2023, Unknowncheats� UKCS #312436
no new posts
belyankin12 | Дата: Суббота, 19.08.2017, 14:02 | Сообщение # 287 |
Трабл с overlay возник. Подключил его, создал кусочек кода с текстом, жму кнопку и игра сразу вылетает, без ошибок. Отключил антивирус, ShadowPlay, гташку чистую поставил, вылетает так же. Использовал ANSI 32 bit AHK, попробовал 32 бит юникод, запускаю игру с включенным скриптом: один раз вылезла ошибка: ссылка, больше я её получить не смог. Потом уже игра вылетать перестала, сейчас уже просто ничего не показывает. АХК выполняется от имени админа, никаких фрапсов и тому подобного нету, чистый экран. Вот код: Код #IfWinActive GTA:SA:MP !Я:: Худ от McFree в .exe работает на ура, а я более чем уверен что там overlay api используется. Кто-то что-то может сказать по этому поводу? Сообщение отредактировал belyankin12 — Суббота, 19.08.2017, 14:03 |
|
|
aknqkzxlcs_21 | Дата: Вторник, 29.08.2017, 22:23 | Сообщение # 292 |
открыл случайно, хотите — допишите сами до полноценной смены скина, ну а мне лень Код CJ() проверяет подключен ли игрок к серверу, заменяет большие конструкции с getPlayerNameById(id) != «» и getPlayerIdByName(name) != -1 Код IsPlayerConnected(player) { Сообщение отредактировал aknqkzxlcs_21 — Среда, 30.08.2017, 16:29 |
|
|
Dworkin | Дата: Пятница, 08.09.2017, 02:25 | Сообщение # 298 |
Не помню откуда у меня эта функция. Код IsLineOfSightClear(startX,startY,startZ,endX,endY,endZ,bCheckBuildings, bCheckVehicles, bCheckPeds, bCheckObjects, bCheckDummies, bSeeThroughStuff, bIgnoreSomeObjectsForCamera) { Пример: Код var := isLineOfSightClear(EnemyposX, EnemyposY, EnemyposZ, MyX, MyY, MyZ,1, 0, 0, 1, 0, 0, 0) IsPlayerVisible(ped) — находится ли пед у вас в зоне экрана(вышей камеры) даже если он за объектами. Код IsPlayerVisible(ped) Сообщение отредактировал Dworkin — Пятница, 08.09.2017, 02:34 |
|
|
Functions
Table of Contents
- Introduction and Simple Examples
- Parameters
- Optional Parameters
- Returning Values to Caller
- Variadic Functions
- Local Variables
- Dynamically Calling a Function
- Short-circuit Boolean Evaluation
- Using Subroutines Within a Function
- Return, Exit, and General Remarks
- Using #Include to Share Functions Among Multiple Scripts
- Libraries of Functions: Standard Library and User Library
- Built-in Functions
Introduction and Simple Examples
A function is similar to a subroutine (Gosub) except that it can accept parameters (inputs) from its caller. In addition, a function may optionally return a value to its caller. Consider the following simple function that accepts two numbers and returns their sum:
Add(x, y) { return x + y ; "Return" expects an expression. }
The above is known as a function definition because it creates a function named «Add» (not case sensitive) and establishes that anyone who calls it must provide exactly two parameters (x and y). To call the function, assign its result to a variable with the := operator. For example:
Var := Add(2, 3) ; The number 5 will be stored in Var.
Also, a function may be called without storing its return value:
Add(2, 3)
But in this case, any value returned by the function is discarded; so unless the function produces some effect other than its return value, the call would serve no purpose.
Since a function call is an expression, any variable names in its parameter list should not be enclosed in percent signs. By contrast, literal strings should be enclosed in double quotes. For example:
if InStr(MyVar, "fox") MsgBox The variable MyVar contains the word fox.
Finally, functions may be called in the parameters of any command (except OutputVar and InputVar parameters such as those of StringLen). However, parameters that do not support expressions must use the «% » prefix as in this example:
MsgBox % "The answer is: " . Add(3, 2)
The «% » prefix is also permitted in parameters that natively support expressions, but it is simply ignored.
Parameters
When a function is defined, its parameters are listed in parentheses next to its name (there must be no spaces between its name and the open-parenthesis). If a function does not accept any parameters, leave the parentheses empty; for example: GetCurrentTimestamp()
.
ByRef Parameters: From the function’s point of view, parameters are essentially the same as local variables unless they are defined as ByRef as in this example:
Swap(ByRef Left, ByRef Right) { temp := Left Left := Right Right := temp }
In the example above, the use of ByRef causes each parameter to become an alias for the variable passed in from the caller. In other words, the parameter and the caller’s variable both refer to the same contents in memory. This allows the Swap function to alter the caller’s variables by moving Left‘s contents into Right and vice versa.
By contrast, if ByRef were not used in the example above, Left and Right would be copies of the caller’s variables and thus the Swap function would have no external effect.
Since return can send back only one value to a function’s caller, ByRef can be used to send back extra results. This is achieved by having the caller pass in a variable (usually empty) in which the function stores a value.
When passing large strings to a function, ByRef enhances performance and conserves memory by avoiding the need to make a copy of the string. Similarly, using ByRef to send a long string back to the caller usually performs better than something like Return HugeString
.
[AHK_L 60+]: If something other than a modifiable variable is passed to a ByRef parameter, the function behaves as though the keyword «ByRef» is absent. For example, Swap(A_Index, i)
stores the value of A_Index in i, but the value assigned to Left is discarded once the Swap function returns.
[v1.1.01+]: The IsByRef() function can be used to determine whether the caller supplied a variable for a given ByRef parameter.
Known limitations:
- Fields of objects are not considered variables for the purposes of ByRef. For example, if
foo.bar
is passed to a ByRef parameter, it will behave as though ByRef was omitted. - It is not possible to pass Clipboard, built-in variables, or environment variables to a function’s ByRef parameter, even when #NoEnv is absent from the script.
- Although a function may call itself recursively, if it passes one of its own local variables or non-ByRef parameters to itself ByRef, the new layer’s ByRef parameter will refer to its own local variable of that name rather than the previous layer’s. However, this issue does not occur when a function passes to itself a global variable, static variable, or ByRef parameter.
- If a parameter in a function-call resolves to a variable (e.g.
Var
or++Var
orVar*=2
), other parameters to its left or right can alter that variable before it is passed to the function. For example,func(Var, Var++)
would unexpectedly pass 1 and 0 when Var is initially 0, even when the function’s first parameter is not ByRef. Since this behavior is counterintuitive, it might change in a future release. - ByRef is not directly supported in functions called by COM clients, or when calling COM methods. Instead, the script receives or must pass a wrapper object containing the VarType and address of the value.
Optional Parameters
When defining a function, one or more of its parameters can be marked as optional. This is done by appending :=
(in [v1.1.09] or later) or =
, followed by the parameter’s default value, which must be one of the following: true
, false
, a literal integer, a literal floating point number, or a quoted/literal string such as «fox» or «» (but strings in versions prior to [v1.0.46.13] support only «»).
The use of =
(without a colon) is permitted for backward-compatibility, but not recommended, and will not be permitted by AutoHotkey v2. Regardless of which operator is used, default values which are strings must always be enclosed in quote marks.
The following function has its Z parameter marked optional:
Add(X, Y, Z:=0) { return X + Y + Z }
When the caller passes three parameters to the function above, Z’s default value is ignored. But when the caller passes only two parameters, Z automatically receives the value 0.
It is not possible to have optional parameters isolated in the middle of the parameter list. In other words, all parameters that lie to the right of the first optional parameter must also be marked optional. [AHK_L 31+]: Optional parameters may be omitted from the middle of the parameter list when calling the function, as shown below. For dynamic function calls and method calls, this requires [v1.1.12+].
Func(1,, 3) Func(X, Y:=2, Z:=0) { ; Note that Z must still be optional in this case. MsgBox %X%, %Y%, %Z% }
[v1.0.46.13+]: ByRef parameters also support default values; for example: Func(ByRef p1 = "")
. Whenever the caller omits such a parameter, the function creates a local variable to contain the default value; in other words, the function behaves as though the keyword «ByRef» is absent.
Returning Values to Caller
As described in introduction, a function may optionally return a value to its caller.
Test := returnTest() MsgBox % Test returnTest() { return 123 }
If you want to return extra results from a function, you may also use ByRef:
returnByRef(A,B,C) MsgBox % A "," B "," C returnByRef(ByRef val1, ByRef val2, ByRef val3) { val1 := "A" val2 := 100 val3 := 1.1 return }
[v1.0.97+]: Objects and Arrays can be used to return multiple values or even named values:
Test1 := returnArray1() MsgBox % Test1[1] "," Test1[2] Test2 := returnArray2() MsgBox % Test2[1] "," Test2[2] Test3 := returnObject() MsgBox % Test3.id "," Test3.val returnArray1() { Test := [123,"ABC"] return Test } returnArray2() { x := 456 y := "EFG" return [x, y] } returnObject() { Test := {id: 789, val: "HIJ"} return Test }
Variadic Functions [AHK_L 60+]
When defining a function, write an asterisk after the final parameter to mark the function as variadic, allowing it to receive a variable number of parameters:
Join(sep, params*) { for index,param in params str .= param . sep return SubStr(str, 1, -StrLen(sep)) } MsgBox % Join("`n", "one", "two", "three")
When a variadic function is called, surplus parameters can be accessed via an object which is stored in the function’s final parameter. The first surplus parameter is at params[1]
, the second at params[2]
and so on. As with any standard object, params.MaxIndex()
can be used to determine the highest numeric index (in this case the number of parameters). However, if there are no parameters, MaxIndex returns an empty string.
Notes:
- The «variadic» parameter can only appear at the end of the formal parameter list.
- RegEx callouts cannot be variadic; the «variadic» parameter is tolerated but left blank.
- Callbacks pass surplus parameters by address rather than via an array.
Variadic Function Calls
While variadic functions can accept a variable number of parameters, an array of parameters can be passed to any function by applying the same syntax to a function-call:
substrings := ["one", "two", "three"] MsgBox % Join("`n", substrings*)
Notes:
- Numbering of parameters within the source array begins at 1.
- Optional parameters may be entirely omitted from the array.
- The array of parameters may contain named items when calling a user-defined function; in any other case, named items are not supported.
- The target function may also be variadic, in which case named items are copied even if they have no corresponding formal parameter.
- This syntax can also be used when calling methods or retrieving properties of objects; for example,
Object.Property[Params*]
. [v1.1.12+]: It can also be used for setting properties.
Known limitations:
- Only the right-most parameter can be expanded this way. For example,
Func(x, y*)
is supported butFunc(x*, y)
is not. - There must not be any non-whitespace characters between the asterisk (
*
) and the symbol which ends the parameter list.
Local and Global Variables
Local Variables
Local variables are specific to a single function and are visible only inside that function. Consequently, a local variable may have the same name as a global variable and both will have separate contents. Separate functions may also safely use the same variable names.
All local variables which are not static are automatically freed (made empty) when the function returns.
Built-in variables such as Clipboard, ErrorLevel, and A_TimeIdle are never local (they can be accessed from anywhere), and cannot be redeclared.
Functions are assume-local by default. Variables accessed or created inside an assume-local function are local by default, with the following exceptions:
- Super-global variables, including classes.
- A dynamic variable reference may resolve to an existing global variable if no local variable exists by that name.
- Commands that create pseudo-arrays may create all elements as global even if only the first element is declared.
The default may also be overridden as shown below (by declaring the variable or by changing the mode of the function).
Force-local mode [v1.1.27+]: If the function’s first line is the word «local», all variable references (even dynamic ones) are assumed to be local unless they are declared as global inside the function. Unlike the default mode, force-local mode has the following behavior:
- Super-global variables (including classes) cannot be accessed without declaring them inside the function.
- Dynamic variable references follow the same rules as non-dynamic ones. Only global variables which are declared inside the function can be accessed.
- StringSplit and other commands which create pseudo-arrays follow the same rules as non-dynamic variable references (avoiding a common source of confusion).
- The LocalSameAsGlobal warning is never raised for variables within a force-local function.
Global variables
To refer to an existing global variable inside a function (or create a new one), declare the variable as global prior to using it. For example:
LogToFile(TextToLog) { global LogFileName ; This global variable was previously given a value somewhere outside this function. FileAppend, %TextToLog%`n, %LogFileName% }
Assume-global mode: If a function needs to access or create a large number of global variables, it can be defined to assume that all its variables are global (except its parameters) by making its first line either the word «global» or the declaration of a local variable. For example:
SetDefaults() { global ; This word may be omitted if the first line of this function will be something like "local MyVar". MyGlobal := 33 ; Assigns 33 to a global variable, first creating the variable if necessary. local x, y:=0, z ; Local variables must be declared in this mode, otherwise they would be assumed global. }
This assume-global mode can also be used by a function to create a global array, such as a loop that assigns values to Array%A_Index%
.
Super-global variables [v1.1.05+]: If a global declaration appears outside of any function, it takes effect for all functions by default (excluding force-local functions). This avoids the need to redeclare the variable in each function. However, if a function parameter or local variable with the same name is declared, it takes precedence over the global variable. Variables created by the class keyword are also super-global.
Static variables
Static variables are always implicitly local, but differ from locals because their values are remembered between calls. For example:
LogToFile(TextToLog) { static LoggedLines = 0 LoggedLines += 1 ; Maintain a tally locally (its value is remembered between calls). global LogFileName FileAppend, %LoggedLines%: %TextToLog%`n, %LogFileName% }
Static Initializers: In versions prior to 1.0.46, all static variables started off blank; so the only way to detect that one was being used for the first time was to check whether it was blank. [v1.0.46+]: A static variable may be initialized to something other than ""
by following it with :=
or =
followed by one of the following: true
, false
, a literal integer, a literal floating point number, or a literal/quoted string such as "fox"
. For example: static X:=0, Y:="fox"
. Each static variable is initialized only once (before the script begins executing).
[AHK_L 58+]: Static var := expression
is supported. All such expressions are evaluated immediately before the script’s auto-execute section in the order they are encountered in the script.
Assume-static mode [v1.0.48+]: A function may be defined to assume that all its variables are static (except its parameters) by making its first line the word «static». For example:
GetFromStaticArray(WhichItemNumber) { static static FirstCallToUs := true ; A static declaration's initializer still runs only once (upon startup). if FirstCallToUs ; Create a static array during the first call, but not on subsequent calls. { FirstCallToUs := false Loop 10 StaticArray%A_Index% := "Value #" . A_Index } return StaticArray%WhichItemNumber% }
In assume-static mode, any variable that should not be static must be declared as local or global (with the same exceptions as for assume-local mode, unless force-local mode is also in effect).
[v1.1.27+]: Force-local mode can be combined with assume-static mode by specifying local
and then static
, as shown below. This allows the function to use force-local rules but create variables as static by default.
global MyVar := "This is global" DemonstrateForceStatic() DemonstrateForceStatic() { local static MyVar := "This is static" ListVars MsgBox }
More about locals and globals
Multiple variables may be declared on the same line by separating them with commas as in these examples:
global LogFileName, MaxRetries := 5 static TotalAttempts = 0, PrevResult
[v1.0.46+]: A local or global variable may be initialized on the same line as its declaration by following it with :=
or =
followed by any expression (the =
operator behaves the same as :=
in declarations). Unlike static initializers, the initializers of locals and globals execute every time the function is called, but only if/when the flow of control actually reaches them. In other words, a line like local x = 0
has the same effect as writing two separate lines: local x
followed by x = 0
.
Because the words local, global, and static are processed immediately when the script launches, a variable cannot be conditionally declared by means of an IF statement. In other words, a declaration inside an IF’s or ELSE’s block takes effect unconditionally for all lines between the declaration and the function’s closing brace. Also note that it is not currently possible to declare a dynamic variable such as global Array%i%
.
For commands that create pseudo-arrays (such as StringSplit), each variable in the resulting pseudo-array is local if the assume-global mode is not in effect or if the pseudo-array’s first element has been declared as a local variable (this is also true if one of the function’s parameters is passed — even if that parameter is ByRef — because parameters are similar to local variables). Conversely, if the first element has been declared global, a global array is created. However, the common source of confusion below applies even in these cases. The first element for StringSplit is ArrayName0. For other array-creating commands such as WinGet List, the first element is ArrayName (i.e. without the number). [v1.1.27+]: When force-local mode is in effect, these commands follow rules consistent with normal variable references; that is, any pseudo-array element not declared as global will be local even if other elements are declared global.
Within a function (unless force-local mode is in effect), any dynamic variable reference such as Array%i%
always resolves to a local variable unless no variable of that name exists, in which case a global is used if it exists. If neither exists and the usage requires the variable to be created, it is created as a local variable unless the assume-global mode is in effect. Consequently, a function can create a global array manually (by means such as Array%i% := A_Index
) only if it has been defined as an assume-global function.
Common source of confusion: Any non-dynamic reference to a variable creates that variable the moment the script launches. For example, when used outside a function, MsgBox %Array1%
creates Array1 as a global the moment the script launches. Conversely, when used inside a function MsgBox %Array1%
creates Array1 as one of the function’s locals the moment the script launches (unless assume-global is in effect), even if Array and Array0 are declared global.
Dynamically Calling a Function
[v1.0.47.06+]: A function (even a built-in function) may be called dynamically via percent signs. For example, %Var%(x, "fox")
would call the function whose name is contained in Var. Similarly, Func%A_Index%()
would call Func1() or Func2(), etc., depending on the current value of A_Index.
[v1.1.07.00+]: Var in %Var%()
can contain a function name or a function object. If the function does not exist, the default base object’s __Call meta-function is invoked instead.
If the function cannot be called due to one of the reasons below, the evaluation of the expression containing the call stops silently and prematurely, which may lead to inconsistent results:
- Calling a nonexistent function, which can be avoided by using
If IsFunc(VarContainingFuncName)
. Except for built-in functions, the called function’s definition must exist explicitly in the script by means such as #Include or a non-dynamic call to a library function. - Passing too few parameters, which can be avoided by checking IsFunc()’s return value (which is the number of mandatory parameters plus one). [v1.0.48+]: Note that passing too many parameters is tolerated; each extra parameter is fully evaluated (including any calls to functions) and then discarded.
Finally, a dynamic call to a function is slightly slower than a normal call because normal calls are resolved (looked up) before the script begins running.
Short-circuit Boolean Evaluation
When AND, OR, and the ternary operator are used within an expression, they short-circuit to enhance performance (regardless of whether any function calls are present). Short-circuiting operates by refusing to evaluate parts of an expression that cannot possibly affect its final result. To illustrate the concept, consider this example:
if (ColorName <> "" AND not FindColor(ColorName)) MsgBox %ColorName% could not be found.
In the example above, the FindColor() function never gets called if the ColorName variable is empty. This is because the left side of the AND would be false, and thus its right side would be incapable of making the final outcome true.
Because of this behavior, it’s important to realize that any side-effects produced by a function (such as altering a global variable’s contents) might never occur if that function is called on the right side of an AND or OR.
It should also be noted that short-circuit evaluation cascades into nested ANDs and ORs. For example, in the following expression, only the leftmost comparison occurs whenever ColorName is blank. This is because the left side would then be enough to determine the final answer with certainty:
if (ColorName = "" OR FindColor(ColorName, Region1) OR FindColor(ColorName, Region2)) break ; Nothing to search for, or a match was found.
As shown by the examples above, any expensive (time-consuming) functions should generally be called on the right side of an AND or OR to enhance performance. This technique can also be used to prevent a function from being called when one of its parameters would be passed a value it considers inappropriate, such as an empty string.
[v1.0.46+]: The ternary conditional operator (?:) also short-circuits by not evaluating the losing branch.
Using Subroutines Within a Function
Although a function cannot contain definitions of other functions, it can contain subroutines. As with other subroutines, use Gosub to launch them and Return to return (in which case the Return would belong to the Gosub and not the function).
Known limitation: Currently, the name of each subroutine (label) must be unique among those of the entire script. The program will notify you upon launch if there are duplicate labels.
If a function uses Gosub to jump to a public subroutine (one that lies outside of the function’s braces), all variables outside are global and the function’s own local variables are not accessible until the subroutine returns. However, A_ThisFunc will still contain the name of the function.
Although Goto cannot be used to jump from inside a function to outside, it is possible for a function to Gosub an external/public subroutine and then do a Goto from there.
Although the use of Goto is generally discouraged, it can be used inside a function to jump to another position within the same function. This can help simplify complex functions that have many points of return, all of which need to do some clean-up prior to returning.
A function may contain externally-called subroutines such as timers, GUI g-labels, and menu items. This is generally done to encapsulate them in a separate file for use with #Include, which prevents them from interfering with the script’s auto-execute section. However, the following limitations apply:
- Such subroutines should use only static and global variables (not locals) if their function is ever called normally. This is because a subroutine thread that interrupts a function-call thread (or vice versa) would be able to change the values of local variables seen by the interrupted thread. Furthermore, any time a function returns to its caller, all of its local variables are made blank to free their memory.
- Such subroutines should use only global variables (not static variables) as GUI control variables.
- When a function is entered by a subroutine thread, any references to dynamic variables made by that thread are treated as globals (including commands that create arrays).
If the flow of execution within a function reaches the function’s closing brace prior to encountering a Return, the function ends and returns a blank value (empty string) to its caller. A blank value is also returned whenever the function explicitly omits Return’s parameter.
When a function uses the Exit command to terminate the current thread, its caller does not receive a return value at all. For example, the statement Var := Add(2, 3)
would leave Var
unchanged if Add()
exits. The same thing happens if a function causes a runtime error such as running a nonexistent file (when UseErrorLevel is not in effect).
A function may alter the value of ErrorLevel for the purpose of returning an extra value that is easy to remember.
To call a function with one or more blank values (empty strings), use an empty pair of quotes as in this example: FindColor(ColorName, "")
.
Since calling a function does not start a new thread, any changes made by a function to settings such as SendMode and SetTitleMatchMode will go into effect for its caller too.
The caller of a function may pass a nonexistent variable or array element to it, which is useful when the function expects the corresponding parameter to be ByRef. For example, calling GetNextLine(BlankArray%i%)
would create the variable BlankArray%i%
automatically as a local or global (depending on whether the caller is inside a function and whether it has the assume-global mode in effect).
When used inside a function, ListVars displays a function’s local variables along with their contents. This can help debug a script.
Style and Naming Conventions
You might find that complex functions are more readable and maintainable if their special variables are given a distinct prefix. For example, naming each parameter in a function’s parameter list with a leading «p» or «p_» makes their special nature easy to discern at a glance, especially when a function has several dozen local variables competing for your attention. Similarly, the prefix «r» or «r_» could be used for ByRef parameters, and «s» or «s_» could be used for static variables.
The One True Brace (OTB) style may optionally be used to define functions. For example:
Add(x, y) { return x + y }
Using #Include to Share Functions Among Multiple Scripts
The #Include directive may be used (even at the top of a script) to load functions from an external file.
Explanation: When the script’s flow of execution encounters a function definition, it jumps over it (using an instantaneous method) and resumes execution at the line after its closing brace. Consequently, execution can never fall into a function from above, nor does the presence of one or more functions at the very top of a script affect the auto-execute section.
Libraries of Functions: Standard Library and User Library [v1.0.47+]
A script may call a function in an external file without having to use #Include. For this to work, a file of the same name as the function must exist in one of the following library directories:
%A_ScriptDir%Lib ; Local library - requires [AHK_L 42+].
%A_MyDocuments%AutoHotkeyLib ; User library.
path-to-the-currently-running-AutoHotkey.exeLib ; Standard library.
For example, if a script calls a nonexistent function MyFunc()
, the program searches for a file named «MyFunc.ahk» in the user library. If not found there, it searches for it in the standard library. If a match is still not found and the function’s name contains an underscore (e.g. MyPrefix_MyFunc
), the program searches both libraries for a file named MyPrefix.ahk
and loads it if it exists. This allows MyPrefix.ahk
to contain both the function MyPrefix_MyFunc
and other related functions whose names start with MyPrefix_
.
[AHK_L 42+]: The local library is supported and is searched before the user library and standard library.
Only a direct function call such as MyFunc()
can cause a library to be auto-included. If the function is only called dynamically or indirectly, such as by a timer or GUI event, the library must be explicitly included in the script. For example: #Include <MyFunc>
Although a library file generally contains only a single function of the same name as its filename, it may also contain private functions and subroutines that are called only by it. However, such functions should have fairly distinct names because they will still be in the global namespace; that is, they will be callable from anywhere in the script.
If a library file uses #Include, the working directory for #Include is the library file’s own directory. This can be used to create a redirect to a larger library file that contains that function and others related to it.
The script compiler (ahk2exe) also supports library functions. However, it requires that a copy of AutoHotkey.exe exist in the directory above the compiler directory (which is normally the case). If AutoHotkey.exe is absent, the compiler still works but library functions are not automatically included.
Functions included from a library perform just as well as other functions because they are pre-loaded before the script begins executing.
Built-in Functions
Any optional parameters at the end of a built-in function’s parameter list may be completely omitted. For example, WinExist("Untitled - Notepad")
is valid because its other three parameters would be considered blank.
A built-in function is overridden if the script defines its own function of the same name. For example, a script could have its own custom WinExist() function that is called instead of the standard one. However, the script would then have no way to call the original function.
External functions that reside in DLL files may be called with DllCall().
To get more details about a particular built-in function below, simply click on its name.
Frequently-used Functions
Function | Description |
---|---|
FileExist | Checks for the existence of a file or folder and returns its attributes. |
GetKeyState | Returns true (1) if the specified key is down and false (0) if it is up. |
InStr | Searches for a given occurrence of a string, from the left or the right. |
RegExMatch | Determines whether a string contains a pattern (regular expression). |
RegExReplace | Replaces occurrences of a pattern (regular expression) inside a string. |
StrLen | Retrieves the count of how many characters are in a string. |
StrReplace | Replaces occurrences of the specified substring with a new string. |
StrSplit | Separates a string into an array of substrings using the specified delimiters. |
SubStr | Retrieves one or more characters from the specified position in a string. |
WinActive | Checks if the specified window exists and is currently active (foremost), and returns its Unique ID (HWND). |
WinExist | Checks if a matching window exists and returns the Unique ID (HWND) of the first matching window. |
Miscellaneous Functions
Function | Description |
---|---|
Asc | Returns the numeric value of the first byte or UTF-16 code unit in the specified string. |
Chr | Returns the string (usually a single character) corresponding to the character code indicated by the specified number. |
DllCall | Calls a function inside a DLL, such as a standard Windows API function. |
Exception | Creates an object which can be used to throw a custom exception. |
FileOpen | Provides object-oriented file I/O. |
Format | Formats a variable number of input values according to a format string. |
Func | Retrieves a reference to the specified function. |
GetKeyName/VK/SC | Retrieves the name/text, virtual key code or scan code of a key. |
IsByRef | Returns a non-zero number if a ByRef parameter of a function was supplied with the specified variable. |
IsFunc | Returns a non-zero number if the specified function exists in the script. |
IsLabel | Returns a non-zero number if the specified label exists in the script. |
IsObject | Returns a non-zero number if the specified value is an object. |
ListView | Functions to add, insert, modify or delete ListView rows/colums, or to get data from them. |
NumGet | Returns the binary number stored at the specified address+offset. |
NumPut | Stores a number in binary format at the specified address+offset. |
OnMessage | Monitors a message/event. |
Ord | Returns the ordinal value (numeric character code) of the first character in the specified string. |
StrGet | Copies a string from a memory address, optionally converting it between code pages. |
StrPut | Copies a string to a memory address, optionally converting it between code pages. |
RegisterCallback | Creates a machine-code address that when called, redirects the call to a function in the script. |
TreeView | Functions to add, modify or delete TreeView items, or to get data from them. |
Trim | Trims characters from the beginning and/or end of a string. |
VarSetCapacity | Enlarges a variable’s holding capacity or frees its memory. |
Math
Function | Description |
---|---|
Abs | Returns the absolute value of Number. |
Ceil | Returns Number rounded up to the nearest integer (without any .00 suffix). |
Exp | Returns e (which is approximately 2.71828182845905) raised to the Nth power. |
Floor | Returns Number rounded down to the nearest integer (without any .00 suffix). |
Log | Returns the logarithm (base 10) of Number. |
Ln | Returns the natural logarithm (base e) of Number. |
Max / Min | Returns the highest/lowest value of one or more numbers. |
Mod | Returns the remainder when Dividend is divided by Divisor. |
Round | Returns Number rounded to N decimal places. |
Sqrt | Returns the square root of Number. |
Sin / Cos / Tan | Returns the trigonometric sine/cosine/tangent of Number. |
ASin / ACos / ATan | Returns the arcsine/arccosine/arctangent in radians. |
Other Functions
Polyethene’s Command Functions: Provides a callable function for each AutoHotkey command that has an OutputVar. This library can be included in any script via #Include.
Posted By: Anonymous
I’m fairly new to autohotkey and ran into a problem recently when trying to pass variables as parameters for the «run» command in autohotkey. Can anyone show me what I’m missing or is this a bug?
Gui, Setup:Add, Edit, w100 vProgram
Gui, Setup:Add, Button, Default w100 gSubmit, OK
Gui, Setup:Show,, Setup
WinWaitClose, Setup
ExitApp
Submit:
Gui, Setup:Submit
RunStuff()
RunStuff() {
Run, %Program%
}
I’ve even tried changing the line to this:
RunStuff() {
run, Program
}
I would really appreciate the help, thanks in advance.
Solution
First things first, while
WinWaitClose, Setup
ExitApp
Is maybe smart thinking, you’re supposed to do this with the GuiClose
event by just defining a function (or a label) with the name GuiClose
.
GuiClose()
{
ExitApp
}
Also, giving the gui a name is redundant, although if you’re planning on adding more guis, fair enough.
And to run cmd commands, you’d start off cmd with the /c
(docs) switch.
Your example netsh wlan connect ssid=%networkname% name=%networkname%
would be done like this:
networkname := "name"
Run, %A_ComSpec% /c netsh wlan connect ssid=%networkname% name=%networkname%
Run, % A_ComSpec " /c netsh wlan connect ssid=" networkname " name=" networkname
The first line is in legacy syntax, I wouldn’t really recommend it.
The second line is in expression syntax.
The built in variable A_ComSpec
(docs) contains the path to cmd.exe.
Example program based on your code to open a file in notepad:
Gui, Setup:Add, Edit, w300 vFilePath, % "C:UsersUserDesktopthis is a text file.txt"
Gui, Setup:Add, Button, Default w100 gSubmit, OK
Gui, Setup:Show, , Setup
return
Submit:
Gui, Setup:Submit
Run, % "notepad.exe """ FilePath """"
return
GuiClose()
{
ExitApp
}
Note how the file path includes spaces, so the argument needs to wrapped in quotes.
""""
may seem weird, but a quote is escaped with another quote in AHK. So outer quotes specify that you’re writing the string, and inner ""
is just one quote escaped. So this produces "
.
Legacy syntax vs modern expression syntax can be a bit confusing when you’re learning AHK. You’ll see a lot of legacy syntax when you look up stuff. This is mainly because AHK was much more popular years and years ago (when legacy syntax was the thing to use).
To get started off on the legacy vs modern expression differences, here’s a pretty good documentation page:
https://www.autohotkey.com/docs/Language.htm
EDIT:
Answer to the new problem that as added in via an edit to the OP.
RunStuff() {
Run, %Program%
}
The variable Program
is not defined in the function’s scope.
Lets consider this example code
var1 := 1
var2 := 2
global var3 := 3
function()
return
function()
{
global var2
MsgBox, % "var1: " var1 "`nvar2: " var2 "`nvar3: " var3 "`n"
}
var1
is not defined in the function’s scope, so nothing will be printed in the message box.
var2
will be used from outside the function’s scope because of the line global var2
.
var3
would also be used from outside of the function scope because var3 was defined as super global. Super global isn’t really recommended, because anything anywhere will use that variable then. Quite easy to run into problems on larger scripts, but it’s convenient for smaller scripts where you know what you’ll be doing and don’t have any external libraries for example.
You can read the related documentation from here:
https://www.autohotkey.com/docs/Functions.htm#Locals
Answered By: Anonymous
Related Articles
- Azure Availability Zone ARM Config
- Maven2: Missing artifact but jars are in place
- How to properly do JSON API GET requests and assign output…
- Azure CLI — az deployment group create -…
- Onclick, the button moves down, why can that due to?
- What are the undocumented features and limitations of the…
- Why does this Azure Resource Manager Template fail…
- Avoid creating new session on each axios request laravel
- Open a column of buttons when another button is clicked…
- How to parse JSON with XE2 dbxJSON
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.