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

Simple math question

Started by Kudendar, 29 February 2012 - 02:31 AM
Kudendar #1
Posted 29 February 2012 - 03:31 AM
Alright well I made a very simple program that digs down a certain amount of blocks based on the number the user inputs. Also it is programmed to record its current position (y) and then subtract the number while it goes up until reaching 0 (which would be its current position). It will do this just fine, until I throw a If statement at the bottom While loop. Then it proceeds to not return to its original spot properly. Sometimes returning to surface double of the distance you input the turtle to dig down…

Heres the code. (Note, Since its such a small program I didnt bother with functions or Events, it is what it is…)

Spoilery = 0
write("Input number of blocks to mine:")
i = tonumber(io.read())
while i > 0 do
turtle.digDown()
turtle.down()
i = i - 1
y = y + 1
print("[DEBUG]\n going down y"..y)
end

print("[DEBUG] BREAK")
while y > 0 do
print(y)
turtle.up()
y = y - 1
–if turtle.up() then y = y - 1 end–
–if not turtle.up() then y = y + 1 end–

end

Now the bottom part is there so that the turtle will go up to where it started, and incase the turtle gets in the way of a mob it will still return to its original spot once the mob is clear from the turtle.

The underlined part will work completely fine if neither of the IF statements are present…But mathmatically…it should not matter. And without these IF statements if the turtle gets caught on a mob in a dungeon it will continue to count down y and eventually stop the turtle from returning to surface

The part that is bolded is the main issue, now the part that is underlined must be taken out depending on what IF statement you use.

Now im sure there is a better way to write the code, but I atleast want to know why the math is so off when using one of the bolded IF statements.

Thanks, Kud.
Luanub #2
Posted 29 February 2012 - 03:56 AM
Not sure if this will solve the problem or not and I'm not anywhere that I can test it at, but give this a try..


if turtle.up() == true then
y = y - 1
elseif turtle.up() ~= true then
y = y + 1
end
Casper7526 #3
Posted 29 February 2012 - 03:58 AM
turtle.up()
y = y - 1
–if turtle.up() then y = y - 1 end–
–if not turtle.up() then y = y + 1 end–


Your moving the turtle up twice if you try one of those statements
Your entire bottom section could be


while y > 0 do
print(y)
if turtle.up() then y = y - 1 end
end

But just so you know if the turtle can't move upwards it will load endlessly and most likely crash ;(
Kudendar #4
Posted 29 February 2012 - 04:19 AM
Ty casper! So then im assuming the If statement will actually call whatever is after the IF. I thought the if statement checked for something then returned whatever was after. Guess not ^_^/>/>.