Main Content

The goto statement in Lua

Archive - Originally posted on "The Horse's Mouth" - 2012-04-06 14:01:26 - Graham Ellis

In the past there was considerable debate in academia and industry on the merits of the use of goto statements, and indeed Lua didn't have them until release 5.2. Well used in Lua, they can provide an escape from inner loops, jumping to a label using a ::label:: format. For example:

  for z=1,10 do
     for y=1,10 do
        for x=1,10 do
           if x^2 + y^2 == z^2 then
              print('found a Pythagorean triple:', x, y, z)
              goto done
           end
        end
     end
  end
  ::done::


You cannot jump into an inner scope which includes local variables, and there are some further (sensible) limitations. This use of the goto to get out of multiple nested loops save you a whole series of nested checks or booleans.

There's a complete example showing sample output too [here].