Switch/Case statement help Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
netaware
Posts: 17
Joined: 29 Apr 2015, 12:52

Switch/Case statement help

Post by netaware » 26 May 2021, 12:31

I'm writing some code and using the Switch/Case statement.
My question is: Can I use wildcards in the case statement? I tried but wasn't getting anywhere.

Code: Select all

var = "all ok"

switch var
{
 case "*ok*" : some command
 case "?ok?": some command
}

User avatar
mikeyww
Posts: 27366
Joined: 09 Sep 2014, 18:38

Re: Switch/Case statement help

Post by mikeyww » 26 May 2021, 13:24

Code: Select all

var = all ok
Switch Instr(var, "ok")
{
 Case 0 : MsgBox, Nope!
 Default: MsgBox, Found it!
}
Explained: Switch

netaware
Posts: 17
Joined: 29 Apr 2015, 12:52

Re: Switch/Case statement help

Post by netaware » 26 May 2021, 13:56

Thanks!
so the CASE command can only contain a text string? or can it contain a variable too?

WatsonEnterprises
Posts: 19
Joined: 25 May 2020, 23:04

Re: Switch/Case statement help  Topic is solved

Post by WatsonEnterprises » 26 May 2021, 14:02

Switch is meant for checking exact values. You probably want a sequence of if/elseifs, or a ternary operator, since it gives you more freedom for what you want to check.

Code: Select all

var := "all ok"

InStr(var, "ok") ? SomeCommand("a")
: (var > 7 && var < 10) ? SomeCommand("b")
: (var = "an exact phrase") ? SomeCommand("c")
: ""  ;default (do nothing)

SomeCommand(param){
	msgbox % param
}

User avatar
JoeWinograd
Posts: 2214
Joined: 10 Feb 2014, 20:00
Location: U.S. Central Time Zone

Re: Switch/Case statement help

Post by JoeWinograd » 26 May 2021, 14:08

netaware wrote:so the CASE command can only contain a text string?
No.
netaware wrote:can it contain a variable too?
Yes...and more...it is an expression:
https://www.autohotkey.com/docs/Language.htm#expressions

Doc is here (and in the CHM Help file that is installed with AHK):
https://www.autohotkey.com/docs/commands/Switch.htm

Also, an article that you may find helpful:
AutoHotkey Switch-Case

Regards, Joe

netaware
Posts: 17
Joined: 29 Apr 2015, 12:52

Re: Switch/Case statement help

Post by netaware » 26 May 2021, 14:17

Thank you for your help!

Now I understand :)

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Switch/Case statement help

Post by swagfag » 26 May 2021, 16:12

u can use wildcards, use regexes instead

Code: Select all

var = "all ok"

switch
{
 case (var ~= "i).+ok.+"): some command
 case (var ~= "i).ok."): some command
}

Post Reply

Return to “Ask for Help (v1)”