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

How can I run 2 loops in parallel?

Started by THC_Butterz, 07 December 2013 - 11:40 AM
THC_Butterz #1
Posted 07 December 2013 - 12:40 PM
I have 2 loops im trying to run at the same time how can I acomplish this?


while true do
	redstone.setOutput("right", true)
	sleep(10)
	redstone.setOutput("right", false)
   sleep(3)
end
while true do
	redstone.setOutput("left", true)
	sleep(1)
	redstone.setOutput("left", false)
	sleep(5)
end

never mind, I was having an issue with my syantax and couldnt get functions to work, I figured it out.
Edited on 07 December 2013 - 12:01 PM
MKlegoman357 #2
Posted 07 December 2013 - 01:09 PM
You can use parallel API. parallel API is an API that allows to run multiple functions at the same time. They don't really run at the same time, parallel API just runs one function until it yields (waits for an event) then runs another function. There are 2 methods in parallel API: parallel.waitForAll and parallel.waitForAny. waitForAll runs all functions until all of them stops or error. waitForAny runs all functions until one of them stops or error. You can run as many functions as you want. To implement that to your code you could use waitForAll:


--// Make your loops inside functions so they could be used by parallel API

local function loop1 ()
  while true do
    redstone.setOutput("right", true)
    sleep(10)
    redstone.setOutput("right", false)
    sleep(3)
  end
end

local function loop2 ()
  while true do
    redstone.setOutput("left", true)
    sleep(1)
    redstone.setOutput("left", false)
    sleep(5)
  end
end

parallel.waitForAll(loop1, loop2) --//This will run both loops.

--//Notice: don't use parenthesis, because you don't want to actually call those functions, only pass them to waitForAll() function
Edited on 07 December 2013 - 12:13 PM