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

How to exit a program?

Started by eastar, 16 June 2015 - 12:56 AM
eastar #1
Posted 16 June 2015 - 02:56 AM
Hi!
I'm using CC1.5. Maybe (probably) I'm just glossing over something… Or it's a programming trick I don't know… How do I terminate a program from inside a program? For example if I press the Q key (os.pullEvent()) the program stops running and then the CraftOS1.5 comes back. How do I do that with a plain grey computer?

Thank you for your answer!
Bomb Bloke #2
Posted 16 June 2015 - 03:00 AM
Well, if you aren't in a function, you can call "return". Personally I just call "error()", which works anywhere.
InDieTasten #3
Posted 16 June 2015 - 03:21 AM
Well, if you aren't in a function, you can call "return". Personally I just call "error()", which works anywhere.
I would not recommend using error for that purpose. It's just the behaviour of the shell that makes it look, as if the program terminated in successful manner, which it effectively isn't.

@easter:
The program should just terminate by reaching the end or returning early. In this manner, your programs is exactly like a function. You retrieve arguments via "…" and can return in any point of your program. Note, that you cannot return directly when inside a nested function.

In your example, the most basic solution would be to "break" out of your event loop:

while(true) do
  e, a, b, c = os.pullEvent()
  if(e == "char" and a == "q") then
    break --# this will effectively jump to ....
  end
  ...
end
--# this point ;)/>
...
eastar #4
Posted 17 June 2015 - 03:37 PM
Thank you the answers! It was just too late and I was too impatient to think about return() and break().
Thanks again!
flaghacker #5
Posted 17 June 2015 - 03:47 PM
Thank you the answers! It was just too late and I was too impatient to think about return() and break().
Thanks again!

They aren't functions, so don't put parentheses behind them, that would just error out.
Creator #6
Posted 17 June 2015 - 05:04 PM

while true do
-- do stuff
  if something then
    break
  end
end
function foo()
return "wow"
end
print(foo())
--> "wow"