Lua goto 文
Lua 言語の goto 文は、制御フローを無条件にラベル付きの文へ移すことを可能にします。
構文
構文の形式は次のとおりです:
goto Label
Label の形式は次のとおりです:
:: Label ::
以下の例では、if 文で goto を使用しています。
例 1
local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- a が 3 より小さいとき、ラベル label にジャンプする
end
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
goto label -- a が 3 より小さいとき、ラベル label にジャンプする
end
出力結果は次のとおりです:
--- goto label --- --- goto label ---
出力結果からわかるように、一回多く出力されています。--- goto label ---。
以下の例では、label 内に複数の文を設定できることを示しています。例 2
i = 0
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() --i が3より大きいとき終了
end
goto s1
::s1:: do
print(i)
i = i+1
end
if i>3 then
os.exit() --i が3より大きいとき終了
end
goto s1
出力結果は次のとおりです:
0 1 2 3
goto があれば、continue の機能を実現できます:
例 3
for i=1, 3 do
if i <= 2 then
print(i, "yes continue")
goto continue
end
print(i, " no continue")
::continue::
print([[i'm end]])
end
if i <= 2 then
print(i, "yes continue")
goto continue
end
print(i, " no continue")
::continue::
print([[i'm end]])
end
出力結果は次のとおりです:
1 yes continue i'm end 2 yes continue i'm end 3 no continue i'm endその他の拡張
Lua ループ