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

How To Make Coroutines Run Together With Events?

Started by exploder, 05 August 2013 - 08:17 AM
exploder #1
Posted 05 August 2013 - 10:17 AM
Hello. I have a problem that I can't solve. I'm trying to make a clock that would refresh every second and print time on screen but when I make coroutine that I put inside my main loop that has an os.pullEvent() then the function won't run every second but only once and that's it. Could you please tell what is the best way to resolve this problem?

Pastebin link: http://pastebin.com/YN6pE8gW – The main loop is at line 122.

Thanks.
GopherAtl #2
Posted 05 August 2013 - 11:13 AM
coroutines aren't functions.

displayTime displays the time, sleeps, and exits. Once it exits, it's coroutine is dead, and it will not run anymore, no matter how many times you try to resume() it.

Coroutines, just like programs, need to contain a loop if they're going to keep running indefinitely.
svdragster #3
Posted 05 August 2013 - 11:18 AM
You have to make a loop in the displayTime function too I guess
exploder #4
Posted 05 August 2013 - 11:50 AM
coroutines aren't functions.

displayTime displays the time, sleeps, and exits. Once it exits, it's coroutine is dead, and it will not run anymore, no matter how many times you try to resume() it.

Coroutines, just like programs, need to contain a loop if they're going to keep running indefinitely.

Then what would be the best way to make that function run every second without interrupting events?

You have to make a loop in the displayTime function too I guess

Well, if I put loop inside there, makes no diffirence.
MysticT #5
Posted 05 August 2013 - 12:17 PM
Use a timer instead of sleep and handle the "timer" event in the main loop. Something like this:

local clockTimer = os.startTimer(1) -- start a timer for 1 second

-- Main loop
while true do
  local evt, p1, p2, p3, p4, p5 = os.pullEvent()
  if evt == "timer" then
    if p1 == clockTimer then
      displayTime() -- redraw the clock
      clockTimer = os.startTimer(1) -- restart the timer
    end
  elseif evt == "some other event" then
    -- handle the event
  end
end
exploder #6
Posted 05 August 2013 - 12:39 PM
Use a timer instead of sleep and handle the "timer" event in the main loop. Something like this:

local clockTimer = os.startTimer(1) -- start a timer for 1 second

-- Main loop
while true do
  local evt, p1, p2, p3, p4, p5 = os.pullEvent()
  if evt == "timer" then
	if p1 == clockTimer then
	  displayTime() -- redraw the clock
	  clockTimer = os.startTimer(1) -- restart the timer
	end
  elseif evt == "some other event" then
	-- handle the event
  end
end

When I tried that last time it didn't work (it wasn't reading mouse x and y positions, etc) but now it worked without errors. Thanks.