Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua goto Statement

Lua goto Statement

Lua loops Lua Loops

The goto statement in the Lua language allows control flow to be transferred unconditionally to a labeled statement.

Syntax

The syntax format is as follows:

goto Label

The format of Label is:

:: Label ::

The following example uses goto in a judgment statement:

Example 1

local

a

=

1

::

label

::

print

(

"--- goto label ---"

)

a

=

a

1

if

a

<

3

then

    goto label  

-- jump to the label label when a is less than 3

end

The output is:

--- goto label ---

--- goto label ---

As can be seen from the output, one extra output --- goto label ---。

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

Example 2

i =

0

::s1::

do

  print

(

i

)

  i = i+

1

end

if

i

3

then

  os.exit

(

)

 

--

i is greater than

3

then exit

end

goto s1

The output 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 is:

1   yes continue

i'm end

2   yes continue

i'm end

3    no continue

i'm end

Lua loops Lua Loops