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

I can't see what is wrong with my code...

Started by Sir.Mongoose, 06 June 2014 - 01:16 AM
Sir.Mongoose #1
Posted 06 June 2014 - 03:16 AM
Okay, I am a beginner in coding in general. But I have been messing with this piece of code for 30 minutes and I can't get it to do what I want it to. What I want the turtle to do is go forward but when it detects a block in front of it, go up. I've got that down, but when it is cornered with a block above it and in front of it I wanted the turtle to turn around and go forward until it detects there is nothing over it. Then I wanted it to go up and turn back around and continue it's journey. The problem is that when it turns around, it does not stop once it detects a free space above it.






local m = 1

function Tforward()
	if turtle.detect() == true then
	  turtle.up()
	end
	if turtle.detect() == true and turtle.detectUp() == true and m == 1 then
	  turtle.turnLeft()
	  turtle.turnLeft()
	  local m = 0
	end
	if turtle.detectUp() == false and m == 0 then
	  turtle.up()
	  turtle.turnRight()
	  turtle.turnRight()		  
	  local m = 1
	end
	turtle.forward()
  end

  while true do
	Tforward()
  end  
Edited on 06 June 2014 - 01:26 AM
Bomb Bloke #2
Posted 06 June 2014 - 03:57 AM
Don't re-declare "m" as local over and over again. Doing so makes a new variable each time that'll be cleared when the current code block ends, rather than sticking with the one you'd already defined - your code hence references three different "m" variables, which happen to share the same name.

Otherwise I believe your code will function in the way you describe, but be aware that if it wanders into a cave system it might get stuck against the roof.
Sir.Mongoose #3
Posted 06 June 2014 - 04:05 AM
Thanks @Bomb Bloke. I'll remember that next time.