TExcelTAD
Home › Lua › Lua goto and Labels

Lua goto and Labels

Lua 5.2 added goto, which jumps to a label in the same function. A label is written ::name::. It sounds old-fashioned, but in Lua it fills two real gaps: there is no continue statement and no way to break out of several nested loops at once.

lua · try it yourself
for i = 1, 5 do
  if i == 3 then goto continue end
  print("processing item", i)
  ::continue::
end
processing item	1
processing item	2
processing item	4
processing item	5

The label ::continue:: sits at the very end of the loop body. Jumping there skips the rest of the current pass and the loop carries on with the next value.

Breaking out of nested loops

break exits only the innermost loop. A goto to a label after the outer loop exits both:

lua · try it yourself
local grid = {
  { 3, 8, 1 },
  { 9, 4, 7 },
  { 2, 6, 5 },
}

local foundRow, foundCol
for r = 1, #grid do
  for c = 1, #grid[r] do
    if grid[r][c] == 7 then
      foundRow, foundCol = r, c
      goto done
    end
  end
end
::done::
print("found 7 at row " .. foundRow .. ", column " .. foundCol)
found 7 at row 2, column 3

Rules

  • A label is visible in the block where it is defined (and nested blocks), but not outside it. You can't jump into a block from outside.
  • You can't jump into the scope of a local variable (past a local declaration that is still in scope at the label).
  • You can't jump to a label in another function.
  • continue is not a keyword, so it makes a good label name.
lua · try it yourself
local code = [[
do
  goto inside
end
do
  ::inside::
end
]]
local ok, err = load(code)
print(err)

local code2 = [[
goto skip
local x = 1
::skip::
print(x)
]]
local ok2, err2 = load(code2)
print(err2)
[string "do..."]:7: no visible label 'inside' for <goto> at line 2
[string "goto skip..."]:4: <goto skip> at line 1 jumps into the scope of local 'x'

Retry loops

goto can also restart a piece of code, for example to retry an operation a few times:

lua · try it yourself
local attempts = 0
local function flakyConnect()
  attempts = attempts + 1
  return attempts >= 3          -- succeeds on the third try
end

::retry::
if not flakyConnect() then
  print("attempt " .. attempts .. " failed, retrying")
  goto retry
end
print("connected after " .. attempts .. " attempts")
attempt 1 failed, retrying
attempt 2 failed, retrying
connected after 3 attempts

A while or repeat loop says the same thing more clearly here; prefer structured loops when they fit, and keep goto for continue and multi-level breaks.

Test yourself

How is a label written in Lua?

  1. label:
  2. ::label::
  3. @label
  4. #label

Which of these is a common use of goto in Lua?

  1. Calling a function
  2. Emulating continue
  3. Jumping into another function
  4. Defining a module

Can goto jump into a block from outside it?

  1. Yes, always
  2. No, labels are only visible in their own block and nested blocks
  3. Only inside loops
  4. Only with goto!