New Switch/Case Command for Alternative Conditions

Helpful script writing tricks and HowTo's
User avatar
jackdunning
Posts: 126
Joined: 01 Aug 2016, 18:17
Contact:

New Switch/Case Command for Alternative Conditions

15 Jan 2020, 09:39

Rather than using a series of If-Else Statements (or the ternary operator), the new Switch command sets up Case statements for alternative results.

In the DateStampConvert.ahk script, the MonthConvert(month) function uses a series of ternary operators to match the text month abbreviation to the corresponding numeral:

Code: Select all

MonthConvert(month)
{
  Global NewMonth
  NewMonth := InStr(month, "jan") ? "01"
    : InStr(month, "feb") ? "02"
    : InStr(month, "mar") ? "03"
    : InStr(month, "apr") ? "04"
    : InStr(month, "may") ? "05"
    : InStr(month, "jun") ? "06"
    : InStr(month, "jul") ? "07"
    : InStr(month, "aug") ? "08"
    : InStr(month, "sep") ? "09"
    : InStr(month, "oct") ? "10"
    : InStr(month, "nov") ? "11"
    : InStr(month, "dec") ? "12"
    :"Not found!"
}
I rewrote the MonthConvert() function for the DateStampConvertSwitch.ahk script using the new AutoHotkey Switch command to replace the cascading ternary operators used in the original DateStampConvert.ahk script.

Code: Select all

MonthConvert(month)
{
	Switch SubStr(month,1,3)
	{	
		Case "jan","ene","jän","gen":Return "01" 
		Case "feb","fév","fev": Return "02"
		Case "mar","mär": Return "03"
		Case "apr","abr","avr": Return "04"
		Case "may","mai","mag": Return "05"
		Case "jun","jui","gui":
			If (SubStr(month,1,4) = "juil")
				 Return "07"
			Else
				 Return "06"
		Case "jul","lug": Return "07"
		Case "aug","ago","aoû","aou","ag": Return "08"
		Case "sep","set": Return "09"
		Case "oct","okt","ott": Return "10"
		Case "nov": Return "11"
		Case "dec","dic","dez","déc": Return "12"
  	}
}
I found that the new syntax made setting up a lookup table of values easier by eliminating the need to carefully track the multiple If-Else statements. I don’t know that it works any better or faster, but the framework makes understanding, implementation, and changing the conditions simpler for the user.

A few basic rules:
  1. A command statement can appear either on the same line as the Case statement (all one line) or start on the next line—including any number of command statements.
  2. Unlike multiple line If-Else statements, Case statements do not require curly brackets to enclose multiple command statement lines. (No need to keep track of curly brackets.)
  3. Up to 20 matching expression values (separated by commas) can appear after the Case command but before the closing colon. These values may come in the form of text, numbers, variables, or functions. The delimiting commas act in the same manner as a logical OR operator between each value (OR or ||) in an If-Else statement.
  4. The Switch-Case condition can either match an optional SwitchValue expressed in the Switch command line (Switch [SwitchValue]) or execute the first Case statement found true.
  5. Although not explicitly stated, the Switch command likely uses Short-circuit Boolean Evaluation. That means after finding a match and executing the enclosed Case commands, AutoHotkey exits the Switch without further evaluation.
  6. It seems that you can add GoTo Labels to the Case statements to allow jumps inside the Switch block. While I haven’t thought through how to use this type of Label jump, AutoHotkey does not support this type of movement between If and Else blocks.
Be sure to update AutoHotkey to the latest release (November 2019) for Switch/Case command support.

Plus, this DateStampConvertSwitch.ahk script, as shown in the Switch statement above, also supports converting dates formatted in Spanish, German, French, and Italian month names. See "Jack's AutoHotkey Blog" (January 13, 2020) for more information.
User avatar
Delta Pythagorean
Posts: 627
Joined: 13 Feb 2017, 13:44
Location: Somewhere in the US
Contact:

Re: New Switch/Case Command for Alternative Conditions

15 Jan 2020, 12:46

Case and Switch was added in 1.1.31.00, relatively new.
With that said, here's the basic documentation on the new items for those who want to know how to use it.

[AHK]......: v2.0.12 | 64-bit
[OS].......: Windows 11 | 23H2 (OS Build: 22621.3296)
[GITHUB]...: github.com/DelPyth
[PAYPAL]...: paypal.me/DelPyth
[DISCORD]..: tophatcat

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

Re: New Switch/Case Command for Alternative Conditions

15 Jan 2020, 12:50

nice writeup, although i wouldnt necessarily recommend using Switch for lookup tables
User avatar
JoeWinograd
Posts: 2182
Joined: 10 Feb 2014, 20:00
Location: U.S. Central Time Zone

Re: New Switch/Case Command for Alternative Conditions

15 Jan 2020, 13:53

Delta Pythagorean wrote:
15 Jan 2020, 12:46
Case and Switch was added in 1.1.31.00, relatively new.
Yes, but there were a couple of serious bugs in it that were fixed in v1.1.31.01, as I mentioned in the 13-Oct-2019 update to my 2-Oct-2019 article:
AutoHotkey Switch-Case

It's working very well now in v1.1.32.00! Regards, Joe
Helgef
Posts: 4709
Joined: 17 Jul 2016, 01:02
Contact:

Re: New Switch/Case Command for Alternative Conditions

16 Jan 2020, 10:32

Hi.
Although not explicitly stated, the Switch command likely uses Short-circuit Boolean Evaluation. That means after finding a match and executing the enclosed Case commands, AutoHotkey exits the Switch without further evaluation.
It is stated in the docs,
Switch wrote: If present, SwitchValue is evaluated once and compared to each case value until a match is found, and then that case is executed. Otherwise, the first case which evaluates to true (non-zero and non-empty) is executed.
It seems that you can add GoTo Labels to the Case statements to allow jumps inside the Switch block. While I haven’t thought through how to use this type of Label jump, AutoHotkey does not support this type of movement between If and Else blocks.
You can,
Switch wrote: As all cases are enclosed in the same block, a label defined in one case can be the target of Goto from another case.
You can use it to, for example, mimic fall-through, eg

Code: Select all

switch "a" {
	case "a":
		; ...
		goto case_b
	case "b":
		case_b:
		; ...
}
Thanks for sharing, cheers.
jsong55
Posts: 224
Joined: 30 Mar 2021, 22:02

Re: New Switch/Case Command for Alternative Conditions

11 Apr 2021, 01:47

Here's a code you can run and read to understand how Switch/Case works.

I personally use this in my GUI when I want a single button to perform multiple actions

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
SetBatchLines -1
#SingleInstance, Force

Gui, New,
Gui, Font, s16
Gui, Add, Button, hwndxxyyzz gBut w45 h45,
GuiButtonIcon(xxyyzz, "dog",, "s45")
Gui, Show, AutoSize
Return

But:
Switch TRUE { ; in the following lines, we're going to look for the Case statements that evaluate to TRUE
    Case GetKeyState("LShift","P") : {
        Msgbox, LShift was pressed
        Msgbox, we can do multiline actions
    }
    Case GetKeyState("LAlt","P") : MsgBox, LAlt was pressed
    Case GetKeyState("LCtrl","P") : Gosub, Hello
    Default : Msgbox, None was pressed  ; when none of the above evaluated to TRUE
}
Return

Hello:
Msgbox, we can launch subroutines too! :)`nBTW, you got here through pressing LCtrl
Return

GuiClose:
ExitApp

; Credits to FanaticGuru
; https://www.autohotkey.com/boards/viewtopic.php?t=1985
GuiButtonIcon(Handle, File, Index := 1, Options := "")
{
	file := A_ScriptDir "\" file  ".ico"
	RegExMatch(Options, "i)w\K\d+", W), (W="") ? W := 16 :
	RegExMatch(Options, "i)h\K\d+", H), (H="") ? H := 16 :
	RegExMatch(Options, "i)s\K\d+", S), S ? W := H := S :
	RegExMatch(Options, "i)l\K\d+", L), (L="") ? L := 0 :
	RegExMatch(Options, "i)t\K\d+", T), (T="") ? T := 0 :
	RegExMatch(Options, "i)r\K\d+", R), (R="") ? R := 0 :
	RegExMatch(Options, "i)b\K\d+", B), (B="") ? B := 0 :
	RegExMatch(Options, "i)a\K\d+", A), (A="") ? A := 4 :
	Psz := A_PtrSize = "" ? 4 : A_PtrSize, DW := "UInt", Ptr := A_PtrSize = "" ? DW : "Ptr"
	VarSetCapacity( button_il, 20 + Psz, 0 )
	NumPut( normal_il := DllCall( "ImageList_Create", DW, W, DW, H, DW, 0x21, DW, 1, DW, 1 ), button_il, 0, Ptr )	; Width & Height
	NumPut( L, button_il, 0 + Psz, DW )		; Left Margin
	NumPut( T, button_il, 4 + Psz, DW )		; Top Margin
	NumPut( R, button_il, 8 + Psz, DW )		; Right Margin
	NumPut( B, button_il, 12 + Psz, DW )	; Bottom Margin	
	NumPut( A, button_il, 16 + Psz, DW )	; Alignment
	SendMessage, BCM_SETIMAGELIST := 5634, 0, &button_il,, AHK_ID %Handle%
	return IL_Add( normal_il, File, Index )
}
User avatar
submeg
Posts: 326
Joined: 14 Apr 2017, 20:39
Contact:

Re: New Switch/Case Command for Alternative Conditions

16 Jun 2021, 06:42

jackdunning wrote:
15 Jan 2020, 09:39

A few basic rules:

Be sure to update AutoHotkey to the latest release (November 2019) for Switch/Case command support.
I didn't realise that it was so new! Similar to @jsong55, I've been using the switch case to give my drop down control on a GUI to switch between different "profiles".

Code: Select all


Switch SetMachineChoice
{
	Case "-1 Test":	;BLANK
	
	MachineChoice := -1
	ModeIs := "BLANK (ALL) Test"
	
	msg := ""
	msg := "Mode: " MachineChoice " | " ModeIs
	
	ToolTip, %msg%
	
	SetTimer, RemoveToolTip, -700
	
	msg := ""
	
	EnabledIcon = %BlankEnabledIcon% 
	DisabledIcon = %BlankDisabledIcon%
	
	IniWrite, %MachineChoice%, %FullPathMCINIFile%, MCSection, MCIs
	
	Return
	
	
	Case "0 BLANK":		;TEST
	
	MachineChoice := 0
	ModeIs := "Test"
	
	msg := ""
	msg := "Mode: " MachineChoice " | " ModeIs
	
	ToolTip, %msg%
	
	SetTimer, RemoveToolTip, -700
	
	msg := ""
	EnabledIcon = %UnknownIcon%
	DisabledIcon = %UnknownDisabledIcon%
	
	IniWrite, %MachineChoice%, %FullPathMCINIFile%, MCSection, MCIs
	
	Return
	
	Case "1 Work":		;Work - Work PC
	
	MachineChoice := 1
	ModeIs := "Work"
	
	msg := ""
	msg := "Mode: " MachineChoice " | " ModeIs
	
	ToolTip, %msg%
	
	SetTimer, RemoveToolTip, -700
	
	msg := ""
	
	EnabledIcon = %WEnabledIcon%
	DisabledIcon = %WDisabledIcon%
	
	IniWrite, %MachineChoice%, %FullPathMCINIFile%, MCSection, MCIs
	
	Return
	
	Case "2 Work (Home PC)":		;Work - Home PC
	
	MachineChoice := 2
	ModeIs := "Work (@home - PC)"
	
	msg := ""
	msg := "Mode: " MachineChoice " | " ModeIs
	
	ToolTip, %msg%
	
	SetTimer, RemoveToolTip, -700
	
	msg := ""
	
	EnabledIcon = %WEnabledIcon%
	DisabledIcon = %WDisabledIcon%
	
	IniWrite, %MachineChoice%, %FullPathMCINIFile%, MCSection, MCIs
	
	Return
	
	Default:
	
	msgbox case error (ModeChoice)
}

Return 

____________________________________
Check out my site, submeg.com
Connect with me on LinkedIn
Courses on AutoHotkey :ugeek:

Return to “Tutorials (v1)”

Who is online

Users browsing this forum: No registered users and 40 guests