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

Self-terminating programs

Started by CastleMan2000, 25 April 2012 - 11:18 PM
CastleMan2000 #1
Posted 26 April 2012 - 01:18 AM
I have a question. Is there a way to stop a program within itself, without CTRL + T? I want a program to be able to terminate itself when the user types a specific command.
Luanub #2
Posted 26 April 2012 - 01:23 AM
try doing something like

if a == 1 then
   error()
end

This might work too

if a == 1 then
   return
end
Edited on 25 April 2012 - 11:23 PM
MysticT #3
Posted 26 April 2012 - 01:28 AM
You have to break the loop that runs the program. Depending on the way your program works and how you implement the commands there's a few ways to do it.
Some exmaples:

while true do
  -- program code --
  if <condition to stop the program> then
    break
  end
end
This way works for simple programs, wich has most of it's code in a loop. It would also work changing the break with a return.


local bExit = false
while not bExit do
  -- program code --
end
This is the one I use, it runs the program until you change the variable "bExit", wich can be changed anywhere in the program, so you can do it in the loop itself or make a function that changes it:

local function exit()
  bExit = true
end
You have several conditions to end the program this way.