autohotkey-2ahk2

Error: This variable has not been assigned a value


I expect this code:

#Requires AutoHotkey v2.0+ 
#SingleInstance Force

ar := [1, 2, 3]

i := 0
:*:ab:: {
  Loop 3 {
    a := StrCompare(ar[i], "Hi")
    Send(a)
    i++
  }    
}

to work the same with

ar := [1, 2, 3]

:*:ab:: {
  Loop 3 {
    a := StrCompare(ar[A_Index], "Hi")
    Send(a)
  }    
}

That is, the result should be 3 negative numbers. Instead it returns this error:

Error: This variable has not been assigned a value.

Specifically: local i  (same name as a global)

    008: Loop 3
    008: {
▶   009: a := StrCompare(ar[i], "Hi")
    010: Send(a)
    011: i++

What happens? I find this similar question but the answer there doesn't explain why the OP made mistake, so I can't learn anything from it.


Solution

  • #Requires AutoHotkey v2.0+ 
    #SingleInstance Force
    
    ar := [1, 2, 3]
    
    i := 0
    :*:ab:: {
      global i ; here
      Loop 3 {
        a := StrCompare(ar[i], "Hi")
        Send(a)
        i++
      }    
    }
    

    See https://www.autohotkey.com/docs/v2/Functions.htm#Locals