Posted 20 January 2014 - 12:19 AM
Tutorial: Lua Basics – Using "break" to Exit Loops
This tutorial is offered as a topic in the Ask A Pro Renewal Project tutorials requested by Lyqyd.
Pre-Requisites: Before reading this tutorial, you should be familiar with all of the control structure concepts covered in [post='16700']Lua Basics – Variable Scope, Code Blocks and Control Structures[/post]
There are three basic looping control structures in Lua: the while loop, the repeat loop and the for loop. Each loop has exit conditions built into the conditions of the control structure. However, it is sometimes useful to exit the loop early, should a special condition arise. That is where the break keyword comes in handy. The break keyword only works inside of the code block of a looping control structure. It will not work with a stand-alone if control structure (that is an if control structure that is not already inside of a loop). Essentially, when Lua encounters a break keyword from within a loop, execution of the loop ceases immediately, and program execution jumps to the next statement following the ending keyword of the loop.
In the case of for and while loops, break will cause program execution to jump to the statement immediately following the end keyword. In the case of repeat loops, break will cause program execution to jump to the statement immediately following the until keyword and its associated condition.
Using break within a while loop
Here is the same program, only this time we will exit the while loop using a break. You will notice it allowed us to get rid of a local variable, get rid of the final else condition, and otherwise made the code slightly more readable.
Other Thoughts
If you are within a function and thinking of exiting a loop in the function, the return keyword will immediately end execution of a loop much like a break will with the added bonus of returning from the function. This may be useful if your purpose is to immediately exit the loop and exit from the function. However, if your function returns values, you will need to handle that within the return statement. If you choose to use return for the purpose of ending loops, make sure that you truly intended to exit the function as well.
Furthermore, it is good to remember that whether you use break or you return, local variables fall out of scope when exiting the code block with which they are associated.
Thanks also to Symmetryc for emphasizing the effect of break and return on variable scope.
This tutorial is offered as a topic in the Ask A Pro Renewal Project tutorials requested by Lyqyd.
Pre-Requisites: Before reading this tutorial, you should be familiar with all of the control structure concepts covered in [post='16700']Lua Basics – Variable Scope, Code Blocks and Control Structures[/post]
There are three basic looping control structures in Lua: the while loop, the repeat loop and the for loop. Each loop has exit conditions built into the conditions of the control structure. However, it is sometimes useful to exit the loop early, should a special condition arise. That is where the break keyword comes in handy. The break keyword only works inside of the code block of a looping control structure. It will not work with a stand-alone if control structure (that is an if control structure that is not already inside of a loop). Essentially, when Lua encounters a break keyword from within a loop, execution of the loop ceases immediately, and program execution jumps to the next statement following the ending keyword of the loop.
In the case of for and while loops, break will cause program execution to jump to the statement immediately following the end keyword. In the case of repeat loops, break will cause program execution to jump to the statement immediately following the until keyword and its associated condition.
Examples
The following examples perform identically.Using break within a while loop
local x = 0
local y = 5
while (x < 10) do
print (x)
if x == y then
break
end
x = x + 1
end -- this is the end of the loop
Using break within a repeat loop
local x = 0
local y = 5
repeat
print (x)
if x == y then
break
end
x = x + 1
until x > 9 -- this is the end of the loop
Using break within a for loop
local x = 0
local y = 5
for x=0,9,1 do
print (x)
if x == y then
break
end
end-- this is the end of the loop
A Better User Menu
In the first tutorial in this series ([post='160662']Lua Basics – Variable Scope, Code Blocks and Control Structures[/post], we looked at using a chained if … elseif … elseif … else … end control structure to create a user menu. We did not use break which would have made our lives a little better. Here is the original code:
--simple user menu without using the break keyword
local choice = false
while (choice == false ) do
print ("1) Walk the dog.")
print ("2) Go to school.")
print ("3) Play Minecraft.")
print ("What would you like to do (1-3)?-->")
local event,char = os.pullEvent("char")
if (char=="1") then
print ("Remember to take plastic bags.")
choice=true
elseif (char =="2") then
print ("Don't forget your backpack.")
choice=true
elseif (char =="3") then
print ("NOW we're talking...")
choice=true
else
print("Please press 1,2, or 3")
end
end
Here is the same program, only this time we will exit the while loop using a break. You will notice it allowed us to get rid of a local variable, get rid of the final else condition, and otherwise made the code slightly more readable.
--simple user menu using the break keyword
while ( true ) do
print ("1) Walk the dog.")
print ("2) Go to school.")
print ("3) Play Minecraft.")
print ("What would you like to do (1-3)?-->")
local event,char = os.pullEvent("char")
if (char=="1") then
print ("Remember to take plastic bags.")
break
elseif (char =="2") then
print ("Don't forget your backpack.")
break
elseif (char =="3") then
print ("NOW we're talking...")
break
end
print("Please press 1,2, or 3")
end
Other Thoughts
If you are within a function and thinking of exiting a loop in the function, the return keyword will immediately end execution of a loop much like a break will with the added bonus of returning from the function. This may be useful if your purpose is to immediately exit the loop and exit from the function. However, if your function returns values, you will need to handle that within the return statement. If you choose to use return for the purpose of ending loops, make sure that you truly intended to exit the function as well.
Furthermore, it is good to remember that whether you use break or you return, local variables fall out of scope when exiting the code block with which they are associated.
Editing Credits
Thanks to theoriginalBit for adding nuance to the discussion on the use of return.Thanks also to Symmetryc for emphasizing the effect of break and return on variable scope.
Edited on 21 January 2014 - 01:02 PM