As you may be aware, a while loop has the structure:
while < some condition is true > do --various statements end
The logic of a while loop can be stated as:
- Test if a condition is logically true. If it is:
- do various statements until you encounter the end of this block (the end statement of the while ... do).
- Jump back up to the beginning of this block (the while statement)
- do various statements until you encounter the end of this block (the end statement of the while ... do).
- If the condition is not logically true, jump to the end of the while block and continue with the rest of the program.
There are two basic approaches to exiting a while loop. -- an exit condition in the while statement itself, or a break condition within the while loop's execution block. Let's try this out using key press events. We will exit if the user presses the "q" key.
Method One: Using an exitCondition within the while statement
local exitConditionVariable = false while not exitConditionVariable do print ("Waiting for a key press...") local _,key = os.pullEvent("key") if key == keys.q then exitConditionVariable = true end print ("Hello from inside of the while loop") end print ("Done")
Method Two: Using an break statement inside of the while loop
The second way is to break out of a while loop when a condition occurs. This does not rely on variables external to the while loop. The break statement will move the program execution counter to one statement past the end statement of the while loop.
while true do -- do this forever print ("Waiting for a key press...") local _,key = os.pullEvent("key") if key == keys.q then break -- will exit the while loop end print ("Hello from inside of the while loop") end print ("Done")
A break statement is immediate. If you try these two versions out, you will find that the print statement print ("Hello from inside of the while loop") will execute one more time in the first example because the while loop will continue to finish execution of all the statements in the while loop before the while condition is tested again. In the break example, when the condition is satisfied, the while loop terminates immediately before printing "Hello from inside of the while loop".
Both are legitimate programming techniques which are used depending on what you as the programmer wish to accomplish.
Additional tutorials that may be helpful if you had this question:
- For more on using break, see Lua Basics: Using break to Exit Loops
- For a good walkthrough of Lua basics, see Lua Basics -- Variable Scope, Code Blocks and Control Structures
Edited by surferpup, 17 February 2014 - 10:09 PM.