6

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.

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Fletcher VK
  • 63
  • 1
  • 4

1 Answers1

5

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.
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Ro Yo Mi
  • 14,790
  • 5
  • 35
  • 43
  • Shorter method for obtaining a Count on an object, save you two/three lines of code: `DesiredDroids.SetCapacity(0)` – errorseven Sep 29 '17 at 00:36
  • 1
    That would work but Object.SetCapacity(0) also truncates unused space. If your object is growing and shrinking a lot over a short period of time you might encounter a performance problem, or worse memory fragmentation (reference [Lexikos's post about half way down](https://autohotkey.com/board/topic/81609-ahk-l-preferred-one-liner-to-empty-object-before-reuse/)) – Ro Yo Mi Sep 29 '17 at 01:45