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

How to Exit from a While Loop

Started by surferpup, 17 February 2014 - 12:59 PM
surferpup #1
Posted 17 February 2014 - 01:59 PM
This very short tutorial came about from a recent question by [member='NMetallic123].

As you may be aware, a [b]while[/b] loop has the structure:

[code]
while < some condition is true > do
–various statements
end
[/code]

The logic of a while loop can be stated as:[list=1]
[*]Test if a condition is logically [b]true[/b]. If it is:
[list]
[*][b]do[/b] various statements until you encounter the end of this block (the [b]end[/b] statement of the [b]while … do[/b]).
[*]Jump back up to the beginning of this block (the [b]while[/b] statement)
[/list]
[*]If the condition is not logically [b]true[/b], jump to the end of the [b]while[/b] block and continue with the rest of the program.
[/list]
[color=#ff0000][i]A [b]while[/b] statement will not execute if the condition evaluates as false at the beginning of the loop.[/i][/color]

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.

A Note on the use of NOTIn the first example, we wrote the exit condition as


while not exitConditionVariable do

Why didn't we just write while exitConditionVariable == false do ??

A variable can be logically false if it is nil or if it is assigned the value of false. However, a variable will equate (==) to false only if it is assigned the value of false. We cover the largest number of possibilities with the first example – not exitConditionVariable will evaluate as true if exitConditionVariable is nil or if it holds a value of false. Because of this, we did not need to declare the variable and set its value before the while loop – although it is better practice to do so.

Using Return to Exit a While LoopIf you are within a function (or program) and thinking of exiting a loop in the function (or program), 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.

Additional tutorials that may be helpful if you had this question:

Edited on 17 February 2014 - 09:09 PM
Bomb Bloke #2
Posted 17 February 2014 - 09:16 PM
There's another method I feel's worth touching on - "return".

If you encapsulate your while loop inside a function, then you can escape it at any time simply by returning from that function.

While this isn't worth doing just for the sake of "getting out of a while loop", it does have its uses when you're buried in a nested loop four or five layers deep and want to escape the lot. "Break" won't work in that circumstance (it'll only let you out of the first), and you'd otherwise have to devote four or five lines to setting "exitConditionVariable"s.

Under later versions of Lua then ComputerCraft uses, "goto" is also an option.
theoriginalbit #3
Posted 17 February 2014 - 09:33 PM
I feel like I should point out to you that the Tutorials section is intended for ComputerCraft specific tutorials not Lua tutorials, there are lots of tutorials out there already for Lua specific information.
surferpup #4
Posted 17 February 2014 - 10:01 PM
I feel like I should point out to you that the Tutorials section is intended for ComputerCraft specific tutorials not Lua tutorials, there are lots of tutorials out there already for Lua specific information.

Given the number of times I have seen this question come up in the Ask-a-Pro, I thought it warranted. Also, the Ask-a-Pro Renewal Project requested good tutorials on beginning Lua.

There's another method I feel's worth touching on - "return".

True, I mention it in the Lua Basics: Using break to Exit Loops. I just thought that given the way I see the question continue to arise, this pretty much covers it. I will amend to point this out as well.
theoriginalbit #5
Posted 17 February 2014 - 10:24 PM
Also, the Ask-a-Pro Renewal Project requested good tutorials on beginning Lua.
where are you getting this information, all I see is information stating that it is ComputerCraft only and at least for now we will not be doing any tutorials on Lua specifics.
surferpup #6
Posted 17 February 2014 - 10:45 PM
where are you getting this information, all I see is information stating that it is ComputerCraft only and at least for now we will not be doing any tutorials on Lua specifics.

I apologize. While it did not say specifically on beginning Lua, [member='Lyqyd'] pointed out: "We've had many new members come through and ask questions, many of them repeats of similar questions that have been asked many times." In reading his post, I interpreted it as a request for a higher quality of tutorials addressing his concern (to lower signal to noise" ratio), as well as on specific topics. There are dozens of questions on Beginning Lua, so I wrote a tutorial on that, explaining the basics of Lua control structures and many of the important key words. In addition to beginning Lua, I have addressed his request for Redstone Basics, and I have almost completed a thorough treatment of Monitor Buttons and Touch Screen Controls.

There is nothing wrong with this tutorial I presented. It answers the question thoroughly, with some thought given to coding practices and an explanation of why things work the way they work. Though I felt it unnecessary, I did include the "return" functionality pointed out by [member='Bomb Bloke']. It also answers a question that has come up repeatedly. A search of "exit from while" or "exiting a while" loop will reveal this tutorial, and answer a user question. Since it is properly answering legitimate new member questions, I felt it was appropriate to write.

I am, quite frankly, surprised at your opposition. Has this somehow violated any of the forum guidelines I have read? The tutorial itself is certainly of high enough quality to be posted in the tutorial section, and on a subject which affects many of the new members. If you feel the quality is poor or the tutorial is inappropriate, then feel free to petition to have it removed. It certainly is not written to create controversy, only to help.
theoriginalbit #7
Posted 17 February 2014 - 10:55 PM
-snip-
Okay firstly I want to say that if my reply came of as hostile it was not my intention. It was my intention however to alert you to the fact that while your tutorials are good — for the most part, a few tweaks here and there never go astray — it is a general rule of the entire ComputerCraft forum that the threads be ComputerCraft related; in my several years on these forums I have seen many a tutorial locked or deleted due to the fact that it was either non-informative or was not ComputerCraft specific where something like the PIL or the likes would have sufficed as opposed to a tutorial.
Secondly I would also like to say that if you expect new users to actually find this tutorial via the search feature you may want to reassess your view/opinion of the ComputerCraft demographic, I'm almost positive that a lot of users are unaware there's a search, let alone thinking of using it! :P/>
Edited on 17 February 2014 - 09:55 PM
surferpup #8
Posted 17 February 2014 - 11:02 PM
Okay firstly I want to say that if my reply came of as hostile it was not my intention.

Fair enough.

It was my intention however to alert you to the fact that while your tutorials are good — for the most part, a few tweaks here and there never go astray

I agree that there is always room for improvement and welcome constructive criticism. You will note that I addressed [member='Bomb Bloke']'s concern, and I am taking the time to address your concerns.

— it is a general rule of the entire ComputerCraft forum that the threads be ComputerCraft related; in my several years on these forums I have seen many a tutorial locked or deleted due to the fact that it was either non-informative or was not ComputerCraft specific where something like the PIL or the likes would have sufficed as opposed to a tutorial.

I hope the tutorial is informative – I realize it only addresses a Lua question – hence the Lua tag. What is a PIL?

Secondly I would also like to say that if you expect new users to actually find this tutorial via the search feature you may want to reassess your view/opinion of the ComputerCraft demographic, I'm almost positive that a lot of users are unaware there's a search, let alone thinking of using it! :P/>

At least I can just copy/paste the link to this when answering the exiting from while question, rather than constantly having to pump out a new answer.
theoriginalbit #9
Posted 17 February 2014 - 11:08 PM
What is a PIL?
It is a very useful reference manual created by the makers of Lua; it stands for Programming in Lua. I myself learnt Lua with the combination of the PIL and a few lua-users.org tutorials.

At least I can just copy/paste the link to this when answering the exiting from while question, rather than constantly having to pump out a new answer.
Well that's the thing, you can always directly link people to your replies on other topics (click the number in the top-right of your reply to get the direct link) — like I've been doing when people are using the Parallel API incorrectly and I link to the functions explanation — or you can link people to the respective section of the PIL.
Edited on 17 February 2014 - 10:09 PM
surferpup #10
Posted 17 February 2014 - 11:12 PM
it stands for Programming in Lua. I myself learnt Lua with the combination of the PIL and a few lua-users.org tutorials.

Ahh. I am well-familiar with the work, not with the acronym. I have spent and continue to spend hours scouring the PIL. I also have spent a good amount of time reading posts, answers to posts and tutorials on this site, as well as in the CC Wiki.

My hope is that by referencing an already-existent tutorial, it will help the new member realize the kinds of resources that are available. One can always hope.