Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the length of an associative array in AutoHotkey?

If you use the length() function on an associative array, it will return the "largest index" in use within the array. So, if you have any keys which are not integers, length() will not return the actual number of elements within your array. (And this could happen for other reasons as well.)

Is there a more useful version of length() for finding the length of an associative array?

Or do I need to actually cycle through and count each element? I'm not sure how I would do that without knowing all of the possible keys beforehand.

like image 985
Fletcher VK Avatar asked Jul 01 '16 00:07

Fletcher VK


1 Answers

If you have a flat array, then Array.MaxIndex() will return the largest integer in the index. However this isn't always the best because AutoHotKey will allow you to have an array whose first index is not 1, so the MaxIndex() could be misleading.

Worse yet, if your object is an associative hashtable where the index may contain strings, then MaxIndex() will return null.

So it's probably best to count them.

DesiredDroids := object()
DesiredDroids["C3P0"] := "Gold"
DesiredDroids["R2D2"] := "Blue&White"
count :=0
for key, value in DesiredDroids
    count++
MsgBox, % "We're looking for " . count . " droid" . ( count=1 ? "" : "s" ) . "."

Output

We're looking for 2 droids.
like image 198
Ro Yo Mi Avatar answered Oct 23 '22 06:10

Ro Yo Mi