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

Lua Timer reset upon interrupt

Started by dzlockhead, 23 April 2012 - 11:51 PM
dzlockhead #1
Posted 24 April 2012 - 01:51 AM
Hello this is my first major program in computercraft, i have some BASIC experience with lua and I am a intermediate programmer at C++, but I am attempting to create a timer that shuts down a program but will reset when interrupted by a redstone signal to the computer, how would i go about doing this?
MysticT #2
Posted 24 April 2012 - 02:39 AM
You have to use events. The basic steps would be:
- Start a timer.
- Wait for an event.
- If the event is timer and it's your timer, exit program.
- If the event is redstone, restart timer.
The code would look something like this:

local exitTime = 10 -- change to whatever you want
local timer = os.startTimer(exitTime) -- starts the timer
while true do
  local evt, arg = os.pullEvent() -- wait for an event
  if evt == "timer" then
	if arg == timer then -- check if it's the correct timer
	  break -- break the loop
	end
  elseif evt == "redstone" then
	timer = os.startTimer(exitTime) -- restarts the timer
  end
end
dzlockhead #3
Posted 24 April 2012 - 04:18 AM
Ok i know its a bit off topic but could you explain to me how events work? Like I said I'm familiar with C++ but not very comfortable with Lua, I can only do very basics.
dzlockhead #4
Posted 24 April 2012 - 03:03 PM
Also would pull event wait for the timer? I dont want execution to stop while the timer is running.
OmegaVest #5
Posted 24 April 2012 - 04:41 PM
os.pullEvent() stops everything until it receives an event. Timer on its own does not. And, you don't have to set the pull as soon as you set the timer, so long as the other parts of the code execute in less time than the timer.

Other than that, you could use the parallel api (specifically parallel.waitForAny() and .waitForAll()), but I have not gotten into that much myself yet. From what I understand, though, you can create a function that will run your code, and have both that and the pullEvent running, and when one yields, they both break.
dzlockhead #6
Posted 24 April 2012 - 06:31 PM
how would I write that so they both break when the one of them yield?
OmegaVest #7
Posted 24 April 2012 - 08:54 PM
Well, as I said, I don't know much about this particular api, but it occurs to me I saw someone use this fragment to great(ish) effect.


function doCode()
   -- The code you want to execute while the timer is active
end

function localTimer(time)
   timer = os.startTimer(time)
   while true do
      event, arg1 = os.pullEvent("timer")
      if arg1 == timer then
         break
      end
   end
end


parallel.waitforAny(doCode(), localTimer(whatTime))  -- whatTime being your 



That should work. The others will correct me if I'm wrong, I hope.