Creating an array using Object notation Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
john_c
Posts: 493
Joined: 05 May 2017, 13:19

Creating an array using Object notation

13 Jul 2020, 04:42

To create an associative array, I use

Code: Select all

Array := {KeyA: ValueA, KeyB: ValueB, ..., KeyZ: ValueZ}
But there is another one notation, the Object one:

Code: Select all

Array := Object("KeyA", ValueA, "KeyB", ValueB, ..., "KeyZ", ValueZ)
What is the purpose to have it? In which cases it will be better?

https://www.autohotkey.com/docs/Objects.htm#Usage_Associative_Arrays
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Creating an array using Object notation  Topic is solved

13 Jul 2020, 09:40

Hi john_c,

Unless I am mistaken both syntax are equivalent (both expressions return the same thing).
As for me, I generally use the first one: after all, you're creating an object not an ordered list - as a list of parameters might still suggest:
capitalCities := {"France": "Paris", "United States": "Washington D.C."}
is structurally equivalent to:
capitalCities := {"United States": "Washington D.C.", "France": "Paris"}
because what matters precisely is the structure, not the relation of order.
As per the link to the documentation you provided, any expression can be used as a key, but to use a variable as a key, it must be enclosed in parentheses. The second syntax, using the Object function, does not have this specificity since function parameters can be expressions:

Code: Select all

obj := Object(f(), "value")
for k, v in obj
	MsgBox % k . "," . v
f() {
return "key"
}
vs:

Code: Select all

obj := {(f()): "value"}
for k, v in obj
	MsgBox % k . "," . v
f() {
return "key"
}
I see at least on case where the second syntax might come in handy: when you may avoid hard coding your associative array.
Actually, Object is a function and, by definition, an array of parameters can be passed to the function by applying the variadic syntax when calling the function. I remember having been astonished by Helgef when he used something like the following:

Code: Select all

letters := "a,A|b,B|c,C"
obj := StrSplit(letters, [",", "|"])
keys := Object(obj*)
for k, v in keys
	MsgBox % k . "," . v
hope this helps

A_AhkUser
my scripts
john_c
Posts: 493
Joined: 05 May 2017, 13:19

Re: Creating an array using Object notation

13 Jul 2020, 10:13

@A_AhkUser Hi, thanks! :-)

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Google [Bot], oktavimark and 329 guests