https://autohotkey.com/docs/Variables.htm
Variables and the % Usage
I integrate here a the Sample from the Official Tutorial
a. When to use percents
One of the most common issues with AutoHotkey involving variables is when to use the percent signs (%). Hopefully this will clear some confusion.
When to use %'s:
- When you are using Commands (see above) you use percent signs.
-- Except when the parameter is OutputVar or InputVar.
- When you are assigning a variable to a value using a traditional mode (an equal sign with no symbol in front of it). Example VarOutput = %VarInput%
When not to use %'s:
- In parameters that are input or output variables, For example: StringLen, OutputVar, InputVar
- On the left side of an assignment: Var = 123abc
- On the left side of traditional (non-expression) if-statements: If Var1 < %Var2%
- Everywhere in expressions. For example:
If (Var1 != Var2)
Var1 := Var2 + 100
Force an expression:
From the Official Help
An expression can be used in a parameter that does not directly support it (except OutputVar parameters) by preceding the expression with a percent sign and a space or tab. In [v1.1.21+], this prefix can be used in the InputVar parameters of all commands except the traditional IF commands (use If (expression) instead). This technique is often used to access arrays. For example:
Code: Select all
FileAppend, % MyArray[i], My File.txt
FileAppend, % MyPseudoArray%i%, My File.txt
MsgBox % "The variable MyVar contains " . MyVar . "."
Loop % Iterations + 1
WinSet, Transparent, % X + 100
Control, Choose, % CurrentSelection - 1
I implement some Examples in the Upcoming Functions
Functions - the Magic Expendable
Here are the Notes for the Official Help.
Official Notes to Functions
USE FUNCTIONS WHENEVER YOU CAN
START USING THEM AS SOON AS POSSIBLE
Functions give you a great flexibility and you can use them for your next project. Maybe with little changes. I not really noticed them a long time , but its really great and it make sense to understand the functions at the start.
Functions are an universal instrument for many things. But the main thing is to automatic Codephrases.
So its possible to do all the Code with no Functions.
There are a bunch of advantages if you use Functions inside the code:
- But your Code is much shorter As bigger your script grow, as more this aspect gets important. Without lose the Overview so quick in case of that.
- Modify the Task getting quite easy
- Use the Functions for your next Project - So if you put energy and work in one Function you can mostly use them inside another Script.
- Safe Time to Navigate inside the Code, Write the Code, Analyzing / debugging
I am know that the starter dont really need functions at the start. But as early you beginn with functions. As quicker you can understand the ahk syntax and you are able to understand the the Examples in the forum better.
Give a function a practical relation. You notice that you are doing the following Codelines again and again
1.)Get the Coordinates from the active Cursor position
2.) Get the Color from the active Cursor position
3.) Compare with 3 Colors If Found the Color
4.) If Found - Wait between 1-2 seconds
5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right.
6.) Output the WaitTime
Copy / Download it and paste it into your Editor. Add the upcoming Changes yourself to for the practice.
Code: Select all
;************************************************
; AHK _ SCRIPT - Introducion Functions
; by HinkerLoden
; 25/03/2016
;************************************************
;************************************************
;Script Global Settings
;************************************************
#NoEnv ; Clear All Systemvariables
#Persistent ;Keeps a script permanently running until ExitApp execute
#SingleInstance force ;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.
;************************************************
;Performance PARAMETERS - if you need speed
;************************************************
;SetBatchLines, -1
;Process, Priority, , L ;A - Max Speed
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, 10, 10 ; for speed -1, -1,
SetMouseDelay, 25 ;0 recommend -1 for max speed
SetDefaultMouseSpeed, 0 ;0-100
;************************************************
;History Protocols
;Switch setting for more Speed
;************************************************
#KeyHistory 1 ; 0 - No Keyhistory
ListLines On ; Off - for more speed
;************************************************
;Window detection
;************************************************
SetTitleMatchMode, 2
SetTitleMatchMode Fast ;slow detect hidden windows
SetWinDelay, 200 ;0 - for more speed
;i double the standard settings to be on the save side
;####################### #######################
; Script Parameter
;####################### #######################
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk
CoordMode, Pixel, Screen
CoordMode, Mouse, Screen
WinMinimizeAll
;####################### #######################
;=============================================================
; Variable Section
;=============================================================
;global
;-------------------------------
;static
;-------------------------------
; Try to avoid pure numbers inside the code - adress all Vars here
Color_Pink = 0xFF00FF
Color_White = 0xFFFFFF
Color_Black = 0x000000
MoveX = 50
MoveX = 50
WaitMin = 1000
WaitMax = 2000
;####################### #######################
;=============================================================
; CODE
;=============================================================
;####################### #######################
F11::
;MouseMove, Coord_X2 ,Coord_Y2 ; uncommend for testing
;Sleep, % Sleeper
MouseGetPos, X_pos,Y_pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_pos, Y_pos ; Get the Color from Mouseposition
; Comparison
If (Color_OutputVar = Color_Pink)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY, ,R
MsgBox, Pink was Found Color:_%Color_OutputVar%
}
If (Color_OutputVar = Color_White)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY, ,R
MsgBox, White was Found Color:_%Color_OutputVar%
}
If (Color_OutputVar = Color_Black)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY,, R
MsgBox, Black was Found Color:_%Color_OutputVar%
}
MsgBox % Color_OutputVar "`n`n" "x_" X_pos "`n" "y_" Y_pos ;Example Forced Expression
return
Structure from a Function
You have 2 parts :
1.) The Function Call inside the Code - Without Braces (only Bracktes)
2.) The Function at end of the Code - Braces include the Code
FunctionName ()
{
X = 5 ;Decline Vars - Cause all Variables are empty inside the Function
Y = 2
Output := X - Y ;a Task
return Output ; Return end the Function a give back ONE Value , but you can do a return without set any Variable / Output Value
}
Everything in the Braces is excecute if you put the Function FunctionName () in the Code. The Script dont stops and go ahead in the next Line.
Functions got there Limitations
Reminder:
- Created Variables are only inside the Function Active
- With return the Functions Stops
- It is not possible to pass Clipboard, built-in variables, or environment variables to a function's ByRef parameter
- Function give the only one Value back
- avoid to use Label / Hotkey / Timer Inside a Function cause you cant get access outside of the function on it
Time to put something into a function. So we analyze first how many steps are done and where the code repeats.
1.)Get the Coordinates from the active Cursor position -1x
2.) Get the Color from the active Cursor position - 1x
3.) Compare with 3 Colors If Found the Color -3x
4.) If Found - Wait between 1-2 seconds -3x
5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 3x
6.) Output the WaitTime -3x
So i paste it into the Example and adding a new Hotkey F12 to get the difference between the Stretched Code without the function and the Reduced Code with using Function
Read the comments. (OLD Code without Functions --> F11 - Same Code Using Functions --> F12)
Function without Output / Input
If you dont want to Use Output or Input Variable. The Function is quite simple. There is nothing inside the Brackets. I take as an example a part from the Code above.
4.) If Found - Wait between 1-2 seconds -3x
5.) Move the Cursor relative from the Position if the Search was sucessfull 50pixel Down and 50pixel Right. 3x
I know, its not the best example (cause we have some inputvariables and its possible to avoid the repeat to put it behind or in front of the comparison )- but i hope you get the point how the structure is how you integrate Functions in your code. And i want to build up on this example.
Code: Select all
;=============================================================
; F 12
;=============================================================
F12::
FunctionsOutput:=F_Sleep_and_Move()
MsgBox, % FunctionsOutput "_" F_Sleep_and_Move() ;Example Forced Expression
/*
%FunctionsOutput% not the same as %F_Sleep_and_Move()% because the Functions runs / Excectuted again. You notice it because the Mouse jumps/move twice !
*/
return
;####################### #######################
;=============================================================
; F U N C T I O N S
;=============================================================
;####################### #######################
F_Sleep_and_Move() ;Output Sleep Time
{
;All inside the Braces Belong to the Function
; () is empty - no variable is send outside of the function into it - so i have to decline them into the function
WaitMin = 1000
WaitMax = 2000
MoveX = 50 ;Negative change the Direction
MoveY = 50
Random, WaitTime , WaitMin, WaitMax
Sleep, % WaitTime
MouseMove, MoveX, MoveY, ,R
return WaitTime ; Output Value is the Variable behind return !
}
Function with Input Variables
Structure:
F_Name (Input1,Input2)
{
Output := Input1 + Input2
return Output
}
Try to Avoid MsgBox or other Visual Outputs inside Functions. It Stops the Script. For testing or debugging you a MsgBox is a good way to locate Issues inside the code.
Try to avoid Number inside Function. Use Imputs Variables to get the Script more Flexible
What i want to show in the next Function:
- Function can used inside other Functions
- String input the need quotation marks "Your String inside quotaion marks"
1.) F_Sleep_and_Move()
Function is now only for the Settings inside the function. So we add these parameters as Inputs that we can use this function flexible for every Movement and every defined time to wait.
So we create a the function:
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Output Sleep Time
{
Random, Wait , WaitMin, WaitMax
Sleep, % Wait
MouseMove, MoveX, MoveY, ,R
return Wait ; Output Value is the Variable behind return !
}
2.) We put the 3 First tasks into one Function -
F_Compare_Color(X,Y,Colorinput,Colorname) and we enhance the Script with a string Input. There we can fill in the NameColor.
A String inside the Function Call need Quotation Marks
Example : F_Compare_Color(Color_Pink,"Pink")
1.)Get the Coordinates from the active Cursor position -1x
2.) Get the Color from the active Cursor position - 1x
3.) Compare with 3 Colors If Found the Color -3x
4.) + 5. ) F_Sleep_and_Move(MoveX,MoveY,WaitMin,WaitMax)
6.) Output the WaitTime -3x Via Message Box
So we add 2 new Functions to the code and implement it
F_CompareCoord_Color(X,Y,Colorinput,Colorname)
{
MouseGetPos, X_Pos,Y_Pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X, Y ; Get the Color from Mouseposition
If ((X=X_Pos) & (Y_pos=Y)) ;Positioncheck
Status=found
; Comparison
If (Color_OutputVar = Colorinput) & (PinkPostionStatus=found)
{
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)
return Colorname
;MsgBox, Colorname was Found Color:_%Color_OutputVar%
}
return NotFound
}
Code: Select all
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Output Sleep Time
{
Random, Wait , WaitMin, WaitMax
Sleep, % Wait
MouseMove, MoveX, MoveY, ,R
return Wait ; Output Value is the Variable behind return !
}
F_Compare_Color(Colorinput,Colorname)
{
MouseGetPos, X_Pos,Y_Pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_Pos, Y_Pos ; Get the Color from Mouseposition
; Comparison
If (Color_OutputVar = Colorinput)
{
; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function
return Colorname
;MsgBox, Colorname was Found Color:_%Color_OutputVar%
}
return 0
}
[hr][/hr]
So the code shrinked a bit .
[code=autohotkey file=F12.ahk]
F12::
StatusPink := F_Compare_Color(Color_Pink,"Pink")
StatusWhite := F_Compare_Color(Color_White,"White")
StatusBlack := F_Compare_Color(Color_Black,"Black")
If (StatusPink OR StatusWhite OR StatusBlack != 0) ;
WaitTime := F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)
MsgBox, % StatusPink "_" StatusWhite "_" StatusBlack "`n`n" Waittime ;Example Forced Expression
Function with Output Variables
Now the final step. We modify the F_Compare_Color(Colorinput,Colorname) that we get the taken Coords out of the Function and the Color. So we get them out of the
If you want to do get a Variable out of a Function you have use the ByRef Parameter
New Function :
F_Compare_Color2(Colorinput,Colorname,ByRef CursorX,ByRef CursorY,ByRef CursorColor)
{
MouseGetPos, CursorX,CursorY ; Get Mouse Coordinates
PixelGetColor, CursorColor,CursorX, CursorY ; Get the Color from Mouseposition
; Comparison
If (CursorColor = Colorinput)
{
; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function
return Colorname
;MsgBox, Colorname was Found Color:_%CursorColor%
}
return 0
}
I only changed the Names inside, because i want to have OutputVars that describe my Output.
The Value i give my ByRef Variables inside the function will
create this variable (or override it) inside the code. So be careful here.
Do not to choose a ByRef Variable what is allready is in use. (or you want to override it )
So here the Final Complete Code
Code: Select all
;************************************************
; AHK _ SCRIPT - Introducion Functions
; by HinkerLoden
; 25/03/2016
;************************************************
;************************************************
;Script Global Settings
;************************************************
#NoEnv ; Clear All Systemvariables
#Persistent ;Keeps a script permanently running until ExitApp execute
#SingleInstance force ;The word FORCE skips the dialog box and replaces the old instance automatically, which is similar in effect to the Reload command.
;************************************************
;Performance PARAMETERS - if you need speed
;************************************************
;SetBatchLines, -1
;Process, Priority, , L ;A - Max Speed
;************************************************
; Input PARAMETERS
;************************************************
SendMode Input
SetKeyDelay, 10, 10 ; for speed -1, -1,
SetMouseDelay, 25 ;0 recommend -1 for max speed
SetDefaultMouseSpeed, 0 ;0-100
;************************************************
;History Protocols
;Switch setting for more Speed
;************************************************
#KeyHistory 1 ; 0 - No Keyhistory
ListLines On ; Off - for more speed
;************************************************
;Window detection
;************************************************
SetTitleMatchMode, 2
SetTitleMatchMode Fast ;slow detect hidden windows
SetWinDelay, 200 ;0 - for more speed
;i double the standard settings to be on the save side
;####################### #######################
; Script Parameter
;####################### #######################
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
;#Include %A_ScriptDir%\YourLibrarys2integrate.ahk
CoordMode, Pixel, Screen
CoordMode, Mouse, Screen
WinMinimizeAll
;####################### #######################
;=============================================================
; Variable Section
;=============================================================
;global
;-------------------------------
;static
;-------------------------------
; Try to avoid pure numbers inside the code - adress all Vars here
Color_Pink = 0xFF00FF
Color_White = 0xFFFFFF
Color_Black = 0x000000
MoveX = 50
MoveY = 50
WaitMin = 1000
WaitMax = 2000
;####################### #######################
;=============================================================
; CODE
;=============================================================
;####################### #######################
F11::
;MouseMove, Coord_X2 ,Coord_Y2 ; uncommend for testing
;Sleep, % Sleeper
MouseGetPos, X_pos,Y_pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_pos, Y_pos ; Get the Color from Mouseposition
; Comparison
If (Color_OutputVar = Color_Pink)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY, ,R
MsgBox, Pink was Found Color:_%Color_OutputVar%
}
If (Color_OutputVar = Color_White)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY, ,R
MsgBox, White was Found Color:_%Color_OutputVar%
}
If (Color_OutputVar = Color_Black)
{
Random, Wait , WaitMin, WaitMax
Sleep , % Wait
MouseMove, MovementFoundX, MovementFoundY,, R
MsgBox, Black was Found Color:_%Color_OutputVar%
}
MsgBox % Color_OutputVar "`n`n" "x_" X_pos "`n" "y_" Y_pos ;Example Forced Expression
return
;=============================================================
; F 12
;=============================================================
F12::
StatusPink := F_Compare_Color2(Color_Pink,"Pink", CursorX,CursorY,CursorColor)
StatusWhite := F_Compare_Color2(Color_White,"White", CursorX,CursorY,CursorColor)
StatusBlack := F_Compare_Color2(Color_Black,"Black", CursorX,CursorY,CursorColor)
If (StatusPink OR StatusWhite OR StatusBlack != 0) ;
{
WaitTime := F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax)
MsgBox, % StatusPink "_" StatusWhite "_" StatusBlack "`n`n" Waittime "`n`n" ;Example Forced Expression
}
If (StatusPink + StatusWhite + StatusBlack = 0 )
MsgBox, % "Nothing Found " "`n`n" "X_" CursorX "`nX_"CursorY "`n`n" CursorColor ;Different Quotations here
/*
%FunctionsOutput% not the same as %F_Sleep_and_Move()% because the Functions runs / Excectuted again. You notice it because the Mouse jumps/move twice !
*/
return
;####################### #######################
;=============================================================
; F U N C T I O N S
;=============================================================
;####################### #######################
F_Sleep_and_Move() ;Output Sleep Time
{
;All inside the Braces Belong to the Function
; () is empty - no variable is send outside of the function into it - so i have to decline them into the function
WaitMin = 1000
WaitMax = 2000
MoveX = 50 ;Negative change the Direction
MoveY = 50
Random, WaitTime , WaitMin, WaitMax
Sleep, % WaitTime
MouseMove, MoveX, MoveY, ,R
return WaitTime ; Output Value is the Variable behind return !
}
F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Output Sleep Time
{
Random, Wait , WaitMin, WaitMax
Sleep, % Wait
MouseMove, MoveX, MoveY, ,R
return Wait ; Output Value is the Variable behind return !
}
F_Compare_Color(Colorinput,Colorname)
{
MouseGetPos, X_Pos,Y_Pos ; Get Mouse Coordinates
PixelGetColor, Color_OutputVar,X_Pos, Y_Pos ; Get the Color from Mouseposition
; Comparison
If (Color_OutputVar = Colorinput)
{
; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function
return Colorname
;MsgBox, Colorname was Found Color:_%Color_OutputVar%
}
return 0
}
F_Compare_Color2(Colorinput,Colorname,ByRef CursorX,ByRef CursorY,ByRef CursorColor)
{
MouseGetPos, CursorX,CursorY ; Get Mouse Coordinates
PixelGetColor, CursorColor,CursorX, CursorY ; Get the Color from Mouseposition
; Comparison
If (CursorColor = Colorinput)
{
; F_Sleep_and_Move2(MoveX,MoveY,WaitMin,WaitMax) ;Possible - Use function in Function
return Colorname
;MsgBox, Colorname was Found Color:_%CursorColor%
}
return 0
}
Hope you get it all. But you will say now. The Long code without Functions is easier. Right. It is. But there are now so many methods to modifiy this script. Reuse it in other Project and add additional task you want.
I give you her some Task to modify the Script. Do it the with the use of functions and without it . You will notice quick the difference.
a.) Add more 5 Colors
Green beige = 0xCCC58F
Beige = 0xD1BC8A
Sand yellow =0xD2B773
Signal yellow =0xF7BA0B
Golden yellow = 0xE2B007
b.) add different Movements
White -> Move 6x 10 Pixel X+Y
Black -> Move 9x 5Pixel X+Y