Call a function whose name is stored in an associative array

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
jmorr
Posts: 28
Joined: 23 Mar 2022, 15:26

Call a function whose name is stored in an associative array

01 May 2024, 00:53

I know I can call a function whose name is stored in a variable, using the syntax %Var%(), but I can't find the right syntax to use when the name is stored in an associative array. Unless the error is somewhere else it's not % Array[Key](). Can anyone help me out?
User avatar
boiler
Posts: 17173
Joined: 21 Dec 2014, 02:44

Re: Call a function whose name is stored in an associative array

01 May 2024, 02:08

You wrap the expression in %, just like with the simple variable, so it would be %Array[Key]%().

Demonstration:

Code: Select all

#Requires AutoHotkey v2.0

FuncNames := Map('MyFunc', 'Func1', 'YourFunc', 'Func2')
%FuncNames['MyFunc']%()
%FuncNames['YourFunc']%()

Func1() {
	MsgBox 'This is function 1'
}

Func2() {
	MsgBox 'This is function 2'
}
Rohwedder
Posts: 7706
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Call a function whose name is stored in an associative array

01 May 2024, 02:23

Hallo.
Or, as this is the v1.1 and older forum:

Code: Select all

#Requires AutoHotkey v1.1.33
FuncNames := {MyFunc:"Func1", YourFunc:"Func2"}

FuncNames.MyFunc()
FuncNames.YourFunc()
; or
; FuncNames["MyFunc"]()
; FuncNames["YourFunc"]()

Func1() {
	MsgBox This is function 1
}

Func2() {
	MsgBox This is function 2
}
User avatar
boiler
Posts: 17173
Joined: 21 Dec 2014, 02:44

Re: Call a function whose name is stored in an associative array

01 May 2024, 02:41

Rohwedder wrote: Or, as this is the v1.1 and older forum:
Oops! Not sure how I missed that. :oops:
User avatar
Chunjee
Posts: 1447
Joined: 18 Apr 2014, 19:05
Contact:

Re: Call a function whose name is stored in an associative array

01 May 2024, 07:51

autohotkey has these things called function objects, you can also put those in an array and call them like so:

Code: Select all

funcObj := func("myCoolFunc")
myArray := {"func1": funcObj, "func2": funcObj, "func3": funcObj}

myArray["func2"].call(10)
; => 20


myCoolFunc(parameter) {
	msgbox, % parameter * 2
}
You may find them documented here: https://www.autohotkey.com/docs/v1/lib/Func.htm

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: AlFlo, arrondark, MerlinSilk, slowwd and 107 guests