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

Help w/ Loops?

Started by moneymaster2012, 19 December 2015 - 09:09 PM
moneymaster2012 #1
Posted 19 December 2015 - 10:09 PM
I am trying to make program (for really reason) where a turtle goes forward, but when it detects a block in front of it, it goes up until it does not detect the block anymore. The problem is, when I run the program, it just goes forward and doesn't go up when it's supposed to.


term.clear()
term.setCursorPos(1,1)
detect = turtle.detect()
  if detect == false then
    turtle.forward(1)
    os.reboot()
  else
    turtle.up(1)
    os.reboot()
  end

Please help if you can.
Dragon53535 #2
Posted 19 December 2015 - 10:34 PM
You need to look at loops…
Also, turtle.up and turtle.forward do not take arguments, they only ever move one block.


while not turtle.forward() do
  turtle.up()
end
That's a simplistic way to do what you want.

Turtle.forward returns a boolean value (true or false) if it could go forward (true) or if it was blocked and could not (false)

while not turtle.forward() do
says keep running the next piece of code, until the correct end block, if the statement is true. The keyword 'not' flips the values of what it affects, false becomes true, true becomes false.
So this code goes and loops and keep going if it can't go forward, until it can.


while not turtle.forward() do
  turtle.up()
end
The turtle.up in there makes the turtle go up, then it hits the end of the loop, and tests the conditional again, and since we're calling the function turtle.forward() it tries to move forward again, and if it can, hey we made it!

Also, please don't, whatever you do, use os.reboot() to loop code…
Edited on 19 December 2015 - 09:34 PM