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

terminating a program mid code based on a condition

Started by firedog2k9, 29 March 2013 - 03:59 PM
firedog2k9 #1
Posted 29 March 2013 - 04:59 PM
basically i'm trying to create a smart program that mines in a shaft-like line. that's not the problem though… i want my program to determine if it has enough fuel to complete the request. so here is my code, the stuff in red is what i want to be the few lines of code that will terminate the whole thing.also, i'm not sure if the rest of the red code will work and i don't have an easy way of testing that atm. any responses are appreciated! thx!!!


term.write("How far do you want me to go? ")
x = read()

if x * 2 > turtle.getFuelLevel() then –*2 because of the final piece of code requires the turtle to move back to where it was placed
print ("Not Enough Fuel!!")
–insert terminating code here–
end

for i = 1, x do
turtle.dig()
while not turtle.forward() do –anti gravel in front
turtle.dig()
end
turtle.digUp()
sleep(.5) –turtle needs this to let gravel drop on top of him
while turtle.detectUp() do –anti gravel on top
turtle.digUp()
end
end

for y = 1, x do –this brings the turtle back to the start of the mining opperation
turtle.back()
end
Kingdaro #2
Posted 29 March 2013 - 05:02 PM
Just use the return keyword.


if x * 2 > turtle.getFuelLevel() then	 --*2 because of the final piece of code requires the turtle to move back to where it was placed
  print ("Not Enough Fuel!!")
  return
end

However, this only works when outside of a function, so if you did this, it wouldn't work.


function checkFuel()
  if x * 2 > turtle.getFuelLevel() then	 --*2 because of the final piece of code requires the turtle to move back to where it was placed
    print ("Not Enough Fuel!!")
    return
  end
end
checkFuel()
print "This text is still printed, the program didn't end."
firedog2k9 #3
Posted 29 March 2013 - 05:23 PM
thanks, as you may tell, i am still learning the whole library of commands and such, but i think I've got my mind wrapped around just the writing aspect of code.

again, much appreciated