How to add maps?

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
iseahound
Posts: 1444
Joined: 13 Aug 2016, 21:04
Contact:

How to add maps?

Post by iseahound » 22 Apr 2021, 19:31

Code: Select all

map1 := map(
   "a","apple",
   "b","banana",
   "c","clementine"
)

map2 := map(
   "d","dragonfruit",
   "e","elderberry",
   "f","fig"
)

map1.set(map2)

MsgBox map1['f']
It's not clear how a map can be added to the other.

User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: How to add maps?

Post by jNizM » 23 Apr 2021, 08:32

Do you want to extend map 2 into map 1?
than this is one way (but it also overwrites existing keys)

Code: Select all

for k, v in map2
	map1.set(k, v)

MsgBox map1["f"]
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile

CptRootBeard
Posts: 26
Joined: 16 Nov 2020, 14:47
Contact:

Re: How to add maps?

Post by CptRootBeard » 23 Apr 2021, 09:00

If you don't want to overwrite existing keys, you just need to use the Has() method.

Code: Select all

;;Only set the value if map1 doesn't have the key
for k, v in map2{
	if !map1.Has(k) {
		map1.set(k, v)
	}
}

MsgBox(map1["f"])

User avatar
kczx3
Posts: 1640
Joined: 06 Oct 2015, 21:39

Re: How to add maps?

Post by kczx3 » 23 Apr 2021, 09:13

Yeah this is a weird question. It seems like you're more asking for operators to work on Maps. Like Map1 + Map2 or something which doesn't exist. @CptRootBeard has the right solution I'd say.

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: How to add maps?

Post by swagfag » 01 May 2021, 16:54

why are u using .Set() for individual key value pairs? set only makes sense if ure about to insert a bunch at a time
if its solely to avoid calling __Item, a better(ie faster) approach would be to coalesce whatever items u need inserted into an array first, then spread the array to .Set(theArray*) them all at once
of course, doing that comes at the expense of memory, but if things got to the point where is a problem, using the original approach would have become a problem much much sooner than that

Post Reply

Return to “Ask for Help (v2)”