Functions - GlitchedSouls/AHK-Guide GitHub Wiki

Functions are great for keeping your code clean and keeping repetitive tasks inside a function that you can call at anytime.

Keeping your code clean.

Let's look at the following script:

; AHK Directives
#SingleInstance, Force
#Warn
CoordMode, Mouse, Client 
CoordMode, Pixel, Client

; Script Specific Global Variables

; OSRS Functions
return 

F1::
	Count = 0
	MouseGetPos, Orig_X, Orig_Y
	x = 100
	y = 100
	Loop 5 {
		MouseMove, x, y
		Msgbox, Mouse has been moved to %x%, %y%.
		x = % x+10
		Random, Time, 300, 600
		Sleep, Time
		Count ++
	}
	Msgbox, You have counted %Count% times so far.
	Loop 5 {
		MouseMove, x, y
		Msgbox, Mouse has been moved to %x%, %y%.
		x = % x+10
		Random, Time, 300, 600
		Sleep, Time
		Count ++
	}
	Msgbox, You have counted %Count% times so far.
	Loop 5 {
		MouseMove, x, y
		Msgbox, Mouse has been moved to %x%, %y%.
		x = % x+10
		Random, Time, 300, 600
		Sleep, Time
		Count ++
	}
	Msgbox, You have counted %Count% times so far.
	MouseMove, Orig_X, Orig_Y
	return

F11::Reload
F12::ExitApp

There is nothing wrong with this script, it runs how I intended and there's nothing we can do to improve it, right? WRONG. Like I mentioned earlier, functions can be used to clean up your script, and if you ever wanted to debug a script later down the line that has hundreds (maybe thousands) of lines of code, it might become unreadable. This is how we can use functions to make our code look pretty.

; AHK Directives
#SingleInstance, Force
#Warn
CoordMode, Mouse, Client 
CoordMode, Pixel, Client

; Script Specific Global Variables
Global Count = 0
Global x
Global y

; OSRS Functions
return 

F1::
	MouseGetPos, Orig_X, Orig_Y
	x = 100
	y = 100
	Loop 3 { 
		Loop 5 {
			myFunctionName()
		}
		Msgbox, You have counted %Count% times so far.
	}
	MouseMove, Orig_X, Orig_Y
	return

F11::Reload
F12::ExitApp

; Functions
	
myFunctionName() {
	MouseMove, x, y
	Msgbox, Mouse has been moved to %x%, %y%.
	x = % x+10
	Random, Time, 300, 600
	Sleep, Time
	Count ++
}

Notice how I've cleaned up the code by moving a chunk of the main code into the myFunctionName(), and condensing the 3 loops into a loop nested in a loop. The variables Count, x and y now have be Global variables so that they can be passed to the function.

You could make the code cleaner than above, but I just wanted show what you can do.

Passing parameters in your function.

Further information

AHK Documentation - Functions