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

Infinite function?

Started by SethShadowrider, 14 October 2012 - 07:18 PM
SethShadowrider #1
Posted 14 October 2012 - 09:18 PM
So im pretty new to creating my own functions and when I try to run my custom one with an argument about the length it just goes infinitely, does anybody know why?

function dig(length)
for i = 1,length do
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnLeft()
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnRight()
turtle.turnRight()
turtle.forward()
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnLeft()
turtle.turnLeft()
turtle.forward()
turtle.turnRight()
end
shell.run("clear")
print("Enter a dig length: ")
local input = read()
dig(input)
end
Kingdaro #2
Posted 14 October 2012 - 09:31 PM
At the end, your function is calling itself.

dig(input)
PixelToast #3
Posted 14 October 2012 - 09:32 PM
you really dont want infinite recursion xD
instead of a function just use

while true do
-- code
end
also you sould use tonumber() to convert the string from read() to a number so you can use it in the for function
Doyle3694 #4
Posted 14 October 2012 - 09:51 PM
So we meet again, stack overflow!
SethShadowrider #5
Posted 14 October 2012 - 10:43 PM
So, I went through and tried to fix those errors, but now the code does nothing when run. It just sits there. This is the code now…

function dig(string)
dist = 0
while dist < length do
dist = dist + 1
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnLeft()
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnRight()
turtle.turnRight()
turtle.forward()
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.turnLeft()
turtle.turnLeft()
turtle.forward()
turtle.turnRight()
end
shell.run("clear")
print("Enter a length")
local length = read()
dig(length)
end
MysticT #6
Posted 14 October 2012 - 10:45 PM
The for loop was fine, the problem is that you need to end the function before asking for input.
It should be:

function dig(length)
  for i = 1,length do
    turtle.dig()
    turtle.forward()
    turtle.digUp()
    turtle.turnLeft()
    turtle.dig()
    turtle.forward()
    turtle.digUp()
    turtle.turnRight()
    turtle.turnRight()
    turtle.forward()
    turtle.dig()
    turtle.forward()
    turtle.digUp()
    turtle.turnLeft()
    turtle.turnLeft()
    turtle.forward()
    turtle.turnRight()
  end
end
term.clear()
term.setCursorPos(1, 1)
print("Enter a dig length: ")
local input = tonumber(read())
dig(input)