English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua goto 文

Lua ループ

Lua言語のgoto文は、制御フローを無条件にマークされた文に転移させることを許可しています。

文法

文法形式は以下の通りです:

goto Label

Labelの形式は以下の通りです:

:: Label ::

以下の例では、判断文の中でgotoを使用しています:

例 1

local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
    goto label   -- a が 3 の時にラベル labelにジャンプします
end
出力結果は:
--- goto label ---
--- goto label ---

から出力結果を見ると、一度多分出力されています --- goto label ---

以下の例では、ラベルに複数の文を設定できることを示しています:

例 2

i = 0
::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

出力結果は:

1   yes continue
i'm end
2   yes continue
i'm end
3    no continue
i'm end

Lua ループ