However you create the list or loop over it, this:
Code: Select all
For k, v in ["cmd.exe","notepad.exe"]
{
WinGet, win, List, ahk_exe %v%
Loop, %win%
{
...
}
}
...is inefficient.
- In the first iteration, WinGet List enumerates all top-level windows, and collects any that belong to cmd.exe.
- In the second iteration, WinGet List enumerates all top-level windows again, and collects any that belong to notepad.exe.
What I would suggest instead is to use a
window group. For example:
Code: Select all
; Define the group only once.
GroupAdd max, ahk_exe cmd.exe
GroupAdd max, ahk_exe notepad.exe
; In place of the For loop:
WinGet win, List, ahk_group max
Loop %win%
{
...
}
Putting that aside...
slyfox1186 wrote: ↑24 Jun 2021, 12:03
My question: Is it possible to use a variable inside the brackets of a for function?
For is not a function and does not have
brackets. Brackets in an expression create an array -
For k, v in [x] is the same as
For k, v in Array(x). If
x contained an array, you would just want
For k, v in x; but in your case it doesn't.
If you want to write an array literal across multiple lines, there are two methods:
continuation lines and
continuation sections.
For example, you can start with a normal array literal like
["cmd.exe", "notepad.exe"], and then add line breaks
before each comma.
Code: Select all
_procNames := ["cmd.exe"
, "console.exe"
, "notepad.exe"
, "notepad++.exe"]
MsgBox % _procNames ; Empty, because objects can't be displayed this way.
for k, v in _procNames
MsgBox % v
But in AutoHotkey v1, you can't put a line break after the
[ or before the
].
Using a continuation section, you can put line breaks wherever you want:
Code: Select all
_procNames := [
(Join
"cmd.exe",
"console.exe",
"notepad.exe",
"notepad++.exe"
)]
Join replaces the physical line break with nothing. Once you're using a continuation section, you may as well change the delimiter:
Code: Select all
_procNames := [
(Join,
"cmd.exe"
"console.exe"
"notepad.exe"
"notepad++.exe"
)]
The delimiter can be any code at all, but whitespace must be escaped (using sequences like `s`t`r`n). This produces an array identical to the previous two:
Code: Select all
_procNames := ["
(LTrim Join","
cmd.exe
console.exe
notepad.exe
notepad++.exe
)"]
This would make a long list more readable, without the need for StrSplit() or similar.
LTrim is needed in this case to avoid putting leading spaces inside the strings.
But if you're just going to loop through it, the older Loop Parse construct may be more efficient and readable:
Code: Select all
_procNames := "
(
cmd.exe
console.exe
notepad.exe
notepad++.exe
)"
MsgBox % _procNames
Loop Parse, % _procNames, `n
MsgBox % A_LoopField
...or the even less forward-compatible version:
Code: Select all
_procNames =
(
cmd.exe
console.exe
notepad.exe
notepad++.exe
)
MsgBox % _procNames
Loop Parse, % _procNames, `n
MsgBox % A_LoopField