Reputation: 26742
Often in my AutoHotkey scripts I need to compare a variable to several values values
if (myString == "val1" || myString == "val2" || myString == "val3" || myString == "val4")
; Do stuff
In most languages, there are ways to make this comparison a bit more concise.
Java
if (myString.matches("val1|val2|val3"))
// Do stuff
Python
if myString in ["val1","val2","val3","val4"]
# Do stuff
Does AutoHotkey have anything similar? Is there a better way to compare a variable against multiple strings?
Upvotes: 1
Views: 2247
Reputation: 1175
; If-Var-In way. Case-insensitive.
Ext := "txt"
If Ext In txt,jpg,png
MsgBox,,, % "Foo"
; RegEx way. Case-insensitive. To make it case-sensitive, remove i).
Ext := "txt"
If (RegExMatch(Ext, "i)^(?:txt|jpg|png)$"))
MsgBox,,, % "Foo"
; Array way 1. Array ways are case-insensitive.
Ext := "txt"
If ({txt: 1, jpg: 1, png: 1}.HasKey(Ext))
MsgBox,,, % "Foo"
; Array way 2.
Extensions := {txt: 1, jpg: 1, png: 1}
Ext := "txt"
If (Extensions[Ext])
MsgBox,,, % "Foo"
If-Var-In is the most native way. However, you should be aware that it isn't an expression, and therefore it cannot be a part of another expression.
Broken:
SomeCondition := True
Extension := "exe"
If (SomeCondition && Extension In "txt,jpg,png")
MsgBox,,, % "Foo"
Else
MsgBox,,, % "Bar"
Works correctly:
SomeCondition := True
Extension := "exe"
If (SomeCondition && RegExMatch(Extension, "i)^(?:txt|jpg|png)$"))
MsgBox,,, % "Foo"
Else
MsgBox,,, % "Bar"
For the same reason (i.e. because it isn't an expression), you cannot you K&R brace style.
Works correctly:
Ext := "txt"
If Ext In txt,jpg,png
MsgBox,,, % "Foo"
Ext := "txt"
If Ext In txt,jpg,png
{
MsgBox,,, % "Foo"
}
Broken:
Ext := "txt"
If Ext In txt,jpg,png {
MsgBox,,, % "Foo"
}
Upvotes: 0
Reputation: 6314
Many different ways.
Autohotkey way (if Var in MatchList)
if myString in val1,val2,val3,val4
Similar to your java regex based way
if (RegExMatch(myString, "val1|val2|val3|val4"))
Similar to your python though not as nice way based on Associative Arrays
if ({val1:1,val2:1,val3:1,val4:1}.hasKey(myString))
Upvotes: 2