A function groups a piece of work under a name so the rest of the script can call it. In v2 the built-in library and your own code follow identical rules, so once you can read one you can read both.
#Requires AutoHotkey v2.0
Initials(fullName)
{
parts := StrSplit(fullName, " ")
out := ""
for word in parts
out .= SubStr(word, 1, 1)
return out
}
MsgBox Initials("Ada Byron Lovelace") ; ABL
Parameters can carry defaults (Greet(name, greeting := "Hello")), and a function that reaches the end without return gives back an empty string.
| Function | Does |
|---|---|
StrLen | Length of a string |
SubStr | Slice by position and length |
StrReplace | Swap one substring for another |
StrSplit | Split into an array |
Trim, LTrim, RTrim | Remove surrounding whitespace |
StrUpper, StrLower | Change case |
InStr | Find a substring |
RegExMatch, RegExReplace | Pattern matching |
Format | Build a string from a template |
Abs, Round, Floor, Ceil, Min, Max, Mod, Random, Sqrt, plus FormatTime and DateAdd for timestamps.
FileRead, FileAppend, FileDelete, FileCopy, FileMove, DirCreate, FileExist and SplitPath cover most disk work. Read once into a variable rather than reopening a file inside a loop.
WinExist, WinActive, WinGetTitle, WinGetPos and ControlGetText return information instead of changing anything, which makes them the natural companions of the actions on the commands page.
SetTimer CheckMail, 60000
CheckMail()
{
ToolTip "Checking…"
Sleep 500
ToolTip
}
A function name used without parentheses is a reference, which is how timers, hotkeys created at runtime and GUI event handlers receive the code they should run.
See the same ideas at full size in examples, or follow the guided path in tutorials.
Write the name, a parameter list in parentheses, then a brace block; use return to hand a value back.
Not by default. Declare the variable with global inside the function, or pass it in as a parameter.
Yes. Use the function name without parentheses, for example SetTimer CheckMail, 60000.