Reputation: 13216
I've been thinking - what is the best way to handle loops in ahk script?
For example instead of:
; Collect results 1
Sleep 1000
Addr1 := IE.document.getElementsByClassName("name")[0].innertext
String_Object := StrSplit(addr1, "`,")
If (Substr(Addr1, 1, 2) = "MK")
{
Addr1 := String_Object[2] . "," . Trim(String_Object[3]) . "," . PostCode
MsgBox, %Addr1%
}
Else
{
Addr1 := String_Object[1] . "," . Trim(String_Object[2]) . "," . PostCode
MsgBox, %Addr1%
}
; Collect results 2
Sleep 1000
Addr2 := IE.document.getElementsByClassName("name")[1].innertext
String_Object := StrSplit(addr2, "`,")
If (Substr(Addr2, 1, 2) = "MK")
{
Addr2 := String_Object[2] . "," . Trim(String_Object[3]) . "," . PostCode
MsgBox, %Addr2%
}
Else
{
Addr2 := String_Object[1] . "," . Trim(String_Object[2]) . "," . PostCode
MsgBox, %Addr2%
}
I'd like to do something like this (note this is pseudocode):
j = 0
i = 1
while (i <= 5)
{
Sleep 1000
Addr[i] := IE.document.getElementsByClassName("name")[j].innertext
String_Object := StrSplit(addr[i], "`,")
If (Substr(Addr[i], 1, 2) = "MK")
{
Addr[i] := String_Object[2] . "," . Trim(String_Object[3]) . "," . PostCode
MsgBox, %Addr[i]%
}
Else
{
Addr[i] := String_Object[1] . "," . Trim(String_Object[2]) . "," . PostCode
MsgBox, %Addr[i]%
}
j = j+1
i = i+1
}
Is it possible to accomplish this in AHK?
Upvotes: 0
Views: 3213
Reputation: 116
I think what you're looking for are Loops and A_Index.
http://www.autohotkey.com/docs/commands/Loop.htm
http://www.autohotkey.com/docs/Variables.htm#Index
A_Index automatically tracks the current loop iteration of the loop in which it exists; it is unique to its loop, and nested loops will track their own A_Index. For an easy example, try the following code:
Loop, 3
{
MsgBox, Outer-loop %A_Index%
Loop, 3
{
MsgBox, Inner-loop %A_Index%
}
}
Based on your pseudocode, you would something to the effect of the following:
Loop, 5
{
Sleep 1000
Addr[A_Index] := IE.document.getElementsByClassName("name")[A_Index - 1].innertext
String_Object := StrSplit(addr[A_Index], "`,")
If (Substr(Addr[A_Index], 1, 2) = "MK")
{
Addr[A_Index] := String_Object[2] . "," . Trim(String_Object[3]) . "," . PostCode
MsgBox, %Addr[A_Index]%
}
Else
{
Addr[A_Index] := String_Object[1] . "," . Trim(String_Object[2]) . "," . PostCode
MsgBox, %Addr[A_Index]%
}
}
Upvotes: 5