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

Lua goto statement

Lua Loops

The goto statement in Lua allows the control flow to be transferred unconditionally to the statement marked with a label.

Syntax

Syntax format as shown below:

goto Label

The format of Label is:

:: Label ::

The following example shows the use of goto in conditional statements:

Example 1

local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
    goto label   -- a is less than 3 jump to the label label when it is time
end
The output result is:
--- goto label ---
--- goto label ---

From the output result, it can be seen that it outputs once more --- goto label ---.

The following example demonstrates that multiple statements can be set in a label:

Example 2

i = 0
::s1:: do
  print(i)
  i = i+1
end
if i>3 then
  os.exit()   -- i is greater than 3 exit at this time
end
goto s1

The output result is:

0
1
2
3

With goto, we can implement the functionality of continue:

Example 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

The output result is:

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

Lua Loops