Jump to content




How can I run 2 loops in parallel?


  • You cannot reply to this topic
1 reply to this topic

#1 THC_Butterz

  • Members
  • 10 posts
  • LocationVirginia, US

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 by THC_Butterz, 07 December 2013 - 01:01 PM.


#2 MKlegoman357

  • Members
  • 1,170 posts
  • LocationKaunas, Lithuania

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 by MKlegoman357, 07 December 2013 - 01:13 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users