Alarms

Note: tested and working on Windows OS; unsure about other OSs.
Here is a simple timer, which should have millisecond accuracy. I’ve not had the ability to test it in situations while the computer would be stressed, so please do try it and critique me if you realize/find a problem.

created = false   -- used to test first use
trigger = false   -- used to test if alarm has triggered
tick = 0          -- you can call on this from the list to see how many times the alarm has started
originTime = 0    -- this is reset every time the alarm goes off and is used as a reference point for the alarm

function alarm(time,list)        -- the first arg is how much time untill firing, and list is your container for the trigger/tick/originTime
	if created == false then     -- set the list to contain the described variables
		list[1] = trigger
		list[2] = originTime
		list[3] = tick
		created = true
		print("alarm created")
	end
	if list[2] == 0 then            -- if the alarm has been fired/started, set the reference point and reset the trigger
		print("alarm checking")
		list[1] = false
		list[2] = os.clock()
		list[3] = list[3] + 1
	elseif os.clock() - list[2] >= time then    -- if the time has reached the time described when the function was run, fire the alarm
		print("alarm fired")
		list[1] = true
		list[2] = 0
	end
end

Example:

myTrigger = {}
alarm(5,myTrigger)             -- Run the alarm to trigger in 5 seconds, list used to check if the alarm completed.
if myTrigger[1] == true then   -- checks to see if the alarm has fired; if so, do stuff
     ...
end
2 Likes