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

Alternating left and right

Started by Kyiki, 20 July 2015 - 10:55 AM
Kyiki #1
Posted 20 July 2015 - 12:55 PM
I'm trying to see if this will work to incorporate into a few things I'm trying to make, but it doesn't seem to cooperate like it looks. It's supposed to change between turning right and left based off x being even or odd. The code look like;


While true do
local x = 1
if (x % 2 == 2) then
turtle.turnLeft()
else
turtle.turnRight()
end
x = x + 1
end

That should turn left, then turn right, then repeat, but from my experience it continues to turn right only. Any advice?
thanks in advance.

Also, sorry for the sloppy looking post, not sure how to put the code in quotes, or how to number the lines on a phone xD sorry
Bomb Bloke #2
Posted 20 July 2015 - 12:58 PM
if (x % 2 == 2) then

x%2 returns the remainder after dividing x by 2. Assuming x is a postive integer, the remainder will only ever be 0 or 1.
MKlegoman357 #3
Posted 20 July 2015 - 01:03 PM
Modulo operator (%) returns the reminder of a division operation. 'x % 2 == 2' will never be true, because that reminder (2) can be divided by 2. You should check against a zero instead. If there will be no reminder after dividing 'x' by 2 then the reminder will be 0. Otherwise, if you cannot evenly divide 'x' by 2 then the reminder won't be 0.
Kyiki #4
Posted 20 July 2015 - 02:19 PM
Oh ok, thanks a lot for the fast responses!
H4X0RZ #5
Posted 20 July 2015 - 05:50 PM
Also you should define the variable outside the loop. Else you will reset the variable every time.