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

Using functions in the turtle code

Started by bozo, 08 November 2012 - 09:26 AM
bozo #1
Posted 08 November 2012 - 10:26 AM
Hello,

I tried to use functions in the turtle code. My aim was to make commands like moving forward more complex. By that I mean that when I'm calling the function moveforward() (just an example) its checks if theres a block infront of the turtle. If there is a block it reacts to it in some way. If theres no block it just moves forward.
And its supposed to do all of this by just calling my function.
How do I do that?

Heres what I did: http://pastebin.com/0HQsV1ss
Kingdaro #2
Posted 08 November 2012 - 10:35 AM
I think I see what you're doing here, going forward if there's no block and spinning if there is a block.

I'd like to make a note that turtle.detect() returns true or false, and not 0 or 1.

Revised code:

local moveforward = function(str)
	if str == "hallo" then
		if not turtle.detect() then -- the "not" keyword is the same as "!" in other languages.
			print("stein")
			turtle.forward()
			return true -- always good to return success where success is found
		else -- no need to check if it's true, because if it's true, it's not going to be false.
			print("kein stein")
			turtle.turnLeft()
			turtle.turnLeft()
			turtle.turnLeft()
			turtle.turnLeft()
			return false -- or return failure where it is found.
		end
	end
end

while true do
	print("gogo")
	moveforward("hallo")
	print("los")
end
bozo #3
Posted 08 November 2012 - 10:48 AM
Thanks for the fast answer! I thought that I get 0 or 1 from the detect function. Now everything works. Thanks again.