Lua goto statement


Release date:2023-09-28 Update date:2023-10-13 Editor:admin View counts:560

Label:

Lua goto statement

In Lua language goto statement allows the control flow to be transferred unconditionally to the marked statement.

Grammar

The syntax format is as follows:

goto Label

The Label format is:

:: Label ::

The following example is used in a judgment statement goto :

Example 1

local a = 1
::label:: print("--- goto label ---")
a = a+1
if a < 3 then
    goto label   -- Jump to label when a is less than 3
end

The output is as follows:

--- goto label ---
--- goto label ---

As can be seen from the output, there is one more output --- goto label --- .

The following example demonstrates the ability to set multiple statements in a lable :

Example 2

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

The output is as follows:

0
1
2
3

With goto , we can implement the function 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 is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).