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

Need an explanation to this little test I wrote using coroutines

Started by SoulSystem, 09 August 2013 - 12:04 AM
SoulSystem #1
Posted 09 August 2013 - 02:04 AM
Here's the code:

	function drawTime()
	  local gameTime = os.time()
	  term.setCursorPos(1, 1)
	  term.clear()
	  term.write(textutils.formatTime(gameTime, false))
	end
	function updateTime()
	  while true do
		os.sleep(4.15) --Yeilds here
		drawTime()
	  end
	end
	function handleEvents()
	  local e = {os.pullEvent()} --Yields here
	  if e[1] == "mouse_click" then
		term.setCursorPos(1, 2)
		print("Click!")
	  end
	end
	--Main Program
	local main = coroutine.create(handleEvents)
	local time = coroutine.create(updateTime)
	local evt = {}
	while true do
	  coroutine.resume(time, unpack(evt))
	  coroutine.resume(main, unpack(evt))
	
	  evt = {os.pullEvent()}
	end
	

Now, my hanldeEvents method only print out "Click!" if I make a mouse click before the very first timer finishes. After the time starts updating, no amount of clicking works. Am I missing a yield somewhere in there that's preventing the print or something? I'm thoroughly confused. Any help on this would be appreciated.

EDIT: The clicks should be clearing every time drawTime is called, which is after every timer event.
immibis #2
Posted 09 August 2013 - 08:58 AM
You're missing a loop in handleEvents.
Why not use the parallel API?
SoulSystem #3
Posted 09 August 2013 - 10:46 AM
Ah, I totally didn't notice the missing loop. Thanks for that. And I'm not using the parallel API simply because I'm playing around with coroutines to get a better understanding of them.