📅  最后修改于: 2023-12-03 15:17:26.885000             🧑  作者: Mango
Loop in AHK is used for repeating one or more lines of code a specific number of times or until certain conditions are met. It is a handy tool for performing repetitive tasks automatically, like iterating through all the elements in an array or looping through a list of files in a folder.
Here's an overview of how to use Loop in AHK:
The basic syntax of a Loop statement in AHK is:
Loop, n
{
; code to be executed n number of times
}
Or
Loop, Parse, string [, delimiter]
{
; code to be executed on each element
}
Where n
is the number of times the code should be executed, string
is the string to be parsed, and delimiter
is the character(s) that separate the elements in the string.
Let's say we want to display a message box 5 times using a Loop. Here's how we can do it:
Loop, 5
{
MsgBox, This is loop number %A_Index%
}
In this example, we're using the Loop
command with the number 5
. The curly brackets contain the code to be executed, which is to display a message box using the MsgBox
command. The %A_Index%
variable returns the current loop index, starting from 1 and incrementing by 1 on each iteration.
Here's an example of how to use Loop to iterate through all the elements in an array:
myArray := ["apple", "banana", "cherry"]
Loop, % myArray.Length()
{
MsgBox, % "Index " . A_Index . ": " . myArray[A_Index - 1]
}
In this example, we're using an array myArray
containing 3 elements. We're using Loop with the myArray.Length()
function as its argument to iterate through all the elements in the array. Inside the code block, we're using the %A_Index%
variable as the index to access each element in the array and display it in a message box.
Here's an example of how to use Loop to loop through all files in a specified folder:
Loop, Files, D:\MyFolder\*, F
{
MsgBox, Found file: %F%
}
In this example, we're using Loop to loop through all files in the D:\MyFolder\
directory. The *
in the second argument tells Loop to look for all files in the folder. Inside the code block, we're using the %F%
variable to display each file's name in a message box.
Loop in AHK is useful for automating repetitive tasks and iterating through lists or arrays. It is a simple yet powerful command that can save programmers time and effort.