Created
June 20, 2013 14:13
-
-
Save blam23/5823067 to your computer and use it in GitHub Desktop.
A timer class for Toribash Comes with helper functions that relate to javascript timing: setInterval, setTimeout, clearInterval, clearTimeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Timer = { } | |
| Timer.__index = Timer | |
| Timer.Count = 0 | |
| function Timer.New(Time, Recurring,Function) | |
| Timer.Count = Timer.Count + 1 | |
| local timer = { } | |
| setmetatable(timer,Timer) | |
| timer.ref = Timer.Count | |
| timer.interval = Time | |
| timer.reoccur = Recurring | |
| timer.func = Function | |
| timer.hooked = false | |
| return timer | |
| end | |
| function Timer:Tick() | |
| local sT = get_world_state().frame_tick | |
| if(self.time <= sT) then | |
| self.func() | |
| if(self.reoccur) then | |
| self.time = get_world_state().frame_tick+self.interval | |
| else | |
| self:Stop() | |
| end | |
| end | |
| end | |
| function Timer:Start() | |
| if(not self.hooked) then | |
| self.time = get_world_state().frame_tick + self.interval | |
| add_hook("draw2d","timer "..self.ref,function() self:Tick() end) | |
| self.hooked = true | |
| end | |
| end | |
| function Timer:Stop() | |
| if(self.hooked) then | |
| remove_hook("draw2d","timer "..self.ref,function() self:Tick() end) | |
| self.hooked = false | |
| end | |
| end | |
| function Timer:Dispose() | |
| remove_hook("draw2d","timer "..self.ref) | |
| self.hooked = false | |
| self = {} | |
| end | |
| -- HELPER FUNCTIONS | |
| -- USABLE JUST LIKE JAVASCRIPT EQUIVALENTS | |
| -- setInterval(function() seconds = seconds + 1 end, 1000) | |
| -- setInterval(Timer.Start, 3000, tmr) | |
| function setInterval(code, millisec, ...) | |
| local t = Timer.New(millisec, true, function() code(unpack(arg)) end) | |
| t:Start() | |
| return t | |
| end | |
| -- timer = setInterval(echo, 1000, "moo") | |
| -- clearTimeout(timer) | |
| clearTimeout = Timer.Stop | |
| -- timeout = setTimeout(echo, 2000, "boo") | |
| -- clearInterval(timer) | |
| clearInterval = Timer.Stop | |
| -- setTimeout(function() echo("Time's up!"); KillEveryone() end, 5000) | |
| -- setTimeout(echo, 5000, "Time's up!") | |
| function setTimeout(code, millisec, ...) | |
| local t = Timer.New(millisec, false, function() code(unpack(arg)) end) | |
| t:Start() | |
| return t | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment