This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
surferpup's profile picture

Lua Basics -- Using "break" to Exit Loops

Started by surferpup, 19 January 2014 - 11:19 PM
surferpup #1
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.

ExamplesThe 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 MenuIn the first tutorial in this series ([post='160662']Lua Basics – Variable Scope, Code Blocks and Control Structures[/post], we looked at using a chained ifelseifelseif elseend 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 CreditsThanks 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
theoriginalbit #2
Posted 20 January 2014 - 12:27 AM
From within functions (and only from within functions), the return keyword will immediately end execution of a loop much like a break will with the added bonus of returning from the function.
Incorrect return works on the main program body as well, run the following code on a computer

if not turtle then
  return print("I'm not a Turtle")
end
print("I'm only printed on a Turtle")

It should also be noted that if a return is used in a do block it will also exit the program

do
  print("I will print")
  return
end
print("I will never print")
Edited on 19 January 2014 - 11:27 PM
surferpup #3
Posted 20 January 2014 - 12:35 AM
You are correct. I was attempting to make the point that return will exit from a loop as well, with the benefit of not only ending the loop but exiting the function.

Changed to"From within functions (and only from within functions)If you are within a function and thinking of exiting a loop in the function…"

I am trying to put together a few Lua basics tutorials for new programmers and those new to Lua. As one who recently took up Lua, these topics would have been helpful for me. Thank you for the correction.
Edited on 19 January 2014 - 11:39 PM
Symmetryc #4
Posted 20 January 2014 - 10:23 AM
From within functions (and only from within functions), the return keyword will immediately end execution of a loop much like a break will with the added bonus of returning from the function.
Incorrect return works on the main program body as well, run the following code on a computer

if not turtle then
  return print("I'm not a Turtle")
end
print("I'm only printed on a Turtle")

It should also be noted that if a return is used in a do block it will also exit the program

do
  print("I will print")
  return
end
print("I will never print")
This works because the main program is essentially a function. You can pass arguments to it and you will get returns much like a normal function. This behavior can be seen when using the loadfile function.

Edit: Furthermore, like a normal function, local variables fall out of scope at the end of its use and arguments are accessed using "…".
Edited on 20 January 2014 - 09:25 AM
surferpup #5
Posted 21 January 2014 - 01:53 PM
I'm not sure what to do with your suggested edit. I am not discussing function arguments in this tutorial … at least I don't think I am. The return discussion is more of an aside.

I added: 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.
Symmetryc #6
Posted 23 January 2014 - 04:05 PM
Sorry, when I wrote "Edit:", I meant that I added onto my original post (I edited it), not to edit your post :P/>
surferpup #7
Posted 24 January 2014 - 12:46 AM
That's okay, I still used one of the nuances you mentioned. :)/>