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

what's a good way to just make a turtle add?

Started by chardo440, 05 December 2013 - 02:35 PM
chardo440 #1
Posted 05 December 2013 - 03:35 PM
I know this is dumb and all but say I just wanted to make a tunneling program and I want to place torches but it needs to keep track of the variable before doing so.

so for example I just want to make the computer go 1 space add to a variable such as x.

x=0

function go()
turtle.forward(x)
x = x + 1
end


print("How many blocks")
input=io.read()
tonumber(input)

for i=input, input do
go()
end
print(x)


however this goes the correct number of blocks I tell it to but when it prints the value and the end its wrong what is happening. Sorry for being got damn tarded.
chardo440 #2
Posted 05 December 2013 - 03:56 PM
function forward(num)
curForw = 1
if num == nil then
num = 1
end
while curForw <= num do
if not turtle.forward() then
turtle.dig()
turtle.attack()
else
curForw = curForw+1
end


here's an example of it but I don't understand why he does what he does can anyone explain please <3
LBPHacker #3
Posted 05 December 2013 - 04:01 PM
-snip-
You should be looping (inside the first loop) until turtle.forward returns true:

function forward(num)
    for ix = 1, (num or 1) do
        while not turtle.forward() do
            turtle.dig()
            turtle.attack()
        end
    end
end
chardo440 #4
Posted 05 December 2013 - 04:13 PM
Thank you. However I don't full understand why the num is in the function. What does that do or where did it ever get its original value. I'm just trying to understand this counting so I can make it to where every 8 blocks or so it'll just place a torch but I want to learn why instead of copying and pasting working code :D/>
Bomb Bloke #5
Posted 05 December 2013 - 05:08 PM
When you call a function, you may pass it values to work with - eg forward(8) passes the "forward" function the number eight. Because the function declaration is termed as "function forward(num)", that number gets copied into the "num" variable so's the rest of the function block can make use of it.

Some notes on your own code:

"turtle.forward()" doesn't make use of values passed to it (it always moves the turtle forward once).

"tonumber", like most functions, does not alter the variable you pass to it. You must capture what it returns in the same manner you used on the above line, eg "input = tonumber(input)". Or you could skip the extra line and just pass the result of "io.read()" directly to the "tonumber()" function - eg, "input = tonumber(io.read())".

"for" loops count from a given value, to a given value. "for i=input, input do" counts from a given value to the same value, meaning the code block will always be executed just once.
chardo440 #6
Posted 05 December 2013 - 06:13 PM
Thank you I'm starting to understand a bit I believe. :D/>