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

Is An Infinite Loop Possible?

Started by Dylan_Madigan, 22 November 2013 - 06:40 AM
Dylan_Madigan #1
Posted 22 November 2013 - 07:40 AM
Ive tryed to make a few programs, such as digital clocks (on monitors), security systems, and networking VIA redstone. They all have various ways of going into an infinite loop of repeating some script, or a part of it, but java always says no after 128 or 256 repeats. Is there any way to keep this from happening, so the computers could be infinitely looping stuff? Im not sure if thats MC its self or Java, but i can only do anything that involves changing something in the server or client. It would be great if its fixable that way.
AgentE382 #2
Posted 22 November 2013 - 09:44 AM
Use the sleep function on each loop iteration.
while true do
  sleep(0)
  doOtherStuff()
end
At least, I think that should work. I've never had an infinite loop fail. Maybe you should streamline your code as well.
Edited on 22 November 2013 - 08:48 AM
Bubba #3
Posted 22 November 2013 - 01:21 PM
Ive tryed to make a few programs, such as digital clocks (on monitors), security systems, and networking VIA redstone. They all have various ways of going into an infinite loop of repeating some script, or a part of it, but java always says no after 128 or 256 repeats. Is there any way to keep this from happening, so the computers could be infinitely looping stuff? Im not sure if thats MC its self or Java, but i can only do anything that involves changing something in the server or client. It would be great if its fixable that way.

From your description of the error, I'm guessing you're getting a stack overflow error. It is true that there is protection built in for infinite looping without yielding (a sleep can act as a yield), but your problem is more along the lines of having a function call another function, or possibly itself, without ever returning anything. After 256 of these successive calls, the stack depth is exceeded.

An example of a bad loop:

function start()
  --do stuff
  start()
end
start()

This will give you a stack overflow error.

A good infinite loop should use a while loop or a repeat until loop like so:

condition = true
value = true
while condition==value do
  --do stuff
end

--A repeat until loop
repeat
  --Repeat some code here
until condition==value

In order for an infinite loop to succeed, it must do what is called "yielding". A yield will allow other code to run in the case of parallel functions, and is required in order to avoid the "too long without yielding" error. A yield can be done a few ways, but the most efficient is like this:

while true do
  --Do stuff
  os.queueEvent("trash_event")
  coroutine.yield()
end
Edited on 22 November 2013 - 12:26 PM