Break statement in Lua Programming

LuaServer Side ProgrammingProgramming

The break statement is used when we want to break or terminate the execution of a loop. Once the break statement is reached, the control is transferred from the current loop to whatever is written after the loop. This statement breaks the inner loop (for,repeat, or while) that contains it; it cannot be used outside a loop. After the break, the program continues running from the point immediately after the broken loop.

A break statement is mostly used in conditional statements and also in loops of all types. It is present in almost all popular programming languages.

Syntax

break

Now, let’s consider a very simple example where we will try to iterate over the elements of an array, and once we found that the current item of the array is equal to a number that we were trying to search, we will break the loop and then print the value of the current element of the array.

Example

Consider the example shown below −

a = {11,12,13,14,15,16,17}
v = 16
local i = 1

while a[i] do
   if a[i] == v then break end
   i = i + 1
end

print(a[i])
print("Completed")

Output

16
Completed

Now let’s consider a more complicated case, where we want to iterate over the elements of an array and break the loop whenever we have encountered a duplicated value.

Example

Consider the example shown below −

iterable = {a=1, doe1={name=1}, doe2={name=2}, doe3={name=2}}
var2 = 1
for i, v in pairs(iterable) do
   print('trying to match', i)
   if string.match(i,'doe') then
      print('match doe', i, v.name, var2)
      if v["name"] == var2 then
         txterr = "Invalid name for "..i
         duplicate = true
         print('found at i=', i)
      end
      if duplicate then
         print('breaking the loop')
         break
      end
   end
end

Output

trying to matchdoe3
match doedoe3  2   1
trying to matchdoe2
match doedoe2  2   1
trying to matcha
trying to matchdoe1
match doedoe1  1   1
found at i=    doe1
breaking the loop
raja
Updated on 01-Dec-2021 10:06:13

Advertisements