Begin
loops with multiple exits ¶カウント・ループの場合、 複数箇所で leave
を使用できます。 begin
ループの場合は、 以下の選択肢があります:
ループ内で exit
を使用(複数記述できます)すると、 ループだけでなくコロン定義全体からも去ります。 例:
: foo begin condition1 while condition2 if exit-code2 exit then condition3 if exit-code3 exit then ... repeat exit-code1 ;
このアプローチの欠点は、 ループ後に共通コードが必要な場合、 共通コードを含む別のワードで foo
を包むか、 または、 それぞれの
exit-code から共通コードを呼び出す必要があることです。
もう 1 つのアプローチは、 begin
ループ内で複数の while
を使用することです。 追加の
while
ごとにループの後ろに then
を追加する必要があります。 例:
begin condition1 while condition2 while condition3 while again then then then
ここでは、 ループの最後に again
を使用して、 各 while
に then
を用意しました。
repeat
は then
を 1 つ減らしますが、 それ以外の場合は同じ動作になります。
これが機能する理由の説明については、 See Arbitrary control structures をご覧下さい。
後で共通のコードを使用することはできますが、 上で示したように、 異なる出口(exit)に対して異なる exit-code を使用することはできません。 以下のようにすると、 これらの異なる exit-code を使用できます:
begin condition1 while condition2 while condition3 while again then exit-code3 else exit-code2 then else exit-code1 then
exit-code は終了条件から比較的離れているため、 これを理解するのは比較的困難です(このような制御構造に慣れていないことも理由にはなりません)。