Compares a value with multiple cases and executes the statements of the first match.
Switch SwitchValue, CaseSense { Case CaseValue1: Statements1 Case CaseValue2a, CaseValue2b: Statements2 Default: Statements3 }
If this and CaseSense are omitted, the first case which evaluates to true (non-zero and non-empty) is executed. Otherwise, SwitchValue is evaluated once and compared to each case value until a match is found, and then that case is executed.
一致するケースがなく、Defaultが存在する場合、そのケースが実行される。
省略したときの初期値はOnです。Otherwise, specify one of the following values, which forces all values to be compared as strings:
On または 1 (true):各比較は大文字と小文字を区別する。
Off or 0 (false): Each comparison is not case-sensitive, i.e. the letters A-Z are considered identical to their lowercase counterparts.
Locale: Each comparison is not case-sensitive according to the rules of the current user's locale. 例えば、英語や西欧のロケールでは、A~Zの小文字だけでなく、ÄやÜなどの非ASCII文字も小文字と同じように扱われることがほとんどです。Localeは、比較する文字列の性質によって、Offの1~8倍遅くなります。
The value to check or compare depending on whether SwitchValue is present.
演算子=や ==と同様に、CaseSenseが省略された場合、SwitchValueとケース値が両方とも純粋な数値である場合、または一方が純粋な数値で他方が数値文字列である場合に数値比較が実行されます。各ケース値は個別に検討され、他のケース値で使用される比較のタイプには影響しない。
CaseSenseパラメータが存在する場合、すべての値は数値ではなく文字列として比較され、SwitchValueまたはCaseValueがオブジェクトとして評価されるとTypeErrorがスローされる。
CaseSenseパラメータが省略された場合、文字列比較はデフォルトで大文字と小文字を区別する。
各ケースは最大20の値をリストすることができる。各値は式でなければならないが、リテラル数値、引用符で囲まれた文字列、変数などの単純なものでもよい。CaseとDefaultはコロンで終了しなければならない。
各ケースの最初の文は、Caseの下か、コロンに続く同じ行に書くことができる。各ケースは、次のCase/ Defaultまたは閉じ中括弧で暗黙のうちに終了する。他のいくつかの言語で見られるswitch文とは異なり、暗黙のフォールスルーはなく、Breakは(ループを囲むループから抜け出す場合を除き)使用されない。
すべてのケースは同じブロックで囲まれているため、あるケースで定義されたラベルは、別のケースからのGotoのターゲットになることができる。しかし、ラベルがCaseまたはDefaultのすぐ上に置かれた場合、次のケースの始まりではなく、前のケースの終わりをターゲットとする。
Defaultは最後に表示される必要はない。
Compares a number with multiple cases and shows the message box of the first match.
switch 2
{
case 1: MsgBox "no match"
case 2: MsgBox "match"
case 3: MsgBox "no match"
}
The SwitchValue parameter can be omitted to execute the first case which evaluates to true.
str := "The quick brown fox jumps over the lazy dog"
switch
{
case InStr(str, "blue"): MsgBox "false"
case InStr(str, "brown"): MsgBox "true"
case InStr(str, "green"): MsgBox "false"
}
この例をテストするには、[の後に以下の略語の1つ、その他の5文字、または Enter/Esc/Tab/.を入力するか、4秒間待つ。
~[::
{
ih := InputHook("V T5 L4 C", "{enter}.{esc}{tab}", "btw,otoh,fl,ahk,ca")
ih.Start()
ih.Wait()
switch ih.EndReason
{
case "Max":
MsgBox 'You entered "' ih.Input '", which is the maximum length of text'
case "Timeout":
MsgBox 'You entered "' ih.Input '" at which time the input timed out'
case "EndKey":
MsgBox 'You entered "' ih.Input '" and terminated it with ' ih.EndKey
default: ; Match
switch ih.Input
{
case "btw": Send "{backspace 3}by the way"
case "otoh": Send "{backspace 4}on the other hand"
case "fl": Send "{backspace 2}Florida"
case "ca": Send "{backspace 2}California"
case "ahk":
Send "{backspace 3}"
Run "https://www.autohotkey.com"
}
}
}