TheIncgi

Timer.lua

Oct 19th, 2020
1,477
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local Timer = advancedMacros.inherit()
  2. Timer. __class = "com.theincgi.Timer"
  3.  
  4. local _new = Timer.new
  5. function Timer:new( sFunc )
  6.   local obj = _new( self )
  7.   if( sFunc == nil )then error("Missing function") end
  8.   obj.func = sFunc
  9.   obj.count = -1
  10.   obj.initDelay = 0
  11.   obj.loopDelay = 0
  12.   obj.exit = false
  13.   obj.isPause = false
  14.   obj.thread = thread.new(function()
  15.     sleep( obj.initDelay )
  16.     local n = 0
  17.     while not obj.exit do
  18.       if obj.count~=-1 and n==obj.count+1 then
  19.         break
  20.       end
  21.       if not obj.isPause then
  22.         --sFunc()
  23.         a,b = pcall(sFunc)
  24.         if not a then
  25.           error("Error occured inside timer function\n"..b)
  26.         end
  27.       end
  28.       n = n+1
  29.       sleep( obj.loopDelay )
  30.     end
  31.   end)
  32.   return obj
  33. end
  34.  
  35. function Timer:setInitDelay( millis )
  36.   assert(self, "Self argument is invalid")
  37.   self.initDelay = millis
  38. end
  39. function Timer:setLoopDelay( millis )
  40.   assert(self, "Self argument is invalid")
  41.   self.loopDelay = millis
  42. end
  43. function Timer:setLoopCount( times )
  44.   assert(self, "Self argument is invalid")
  45.   self.count = times
  46. end
  47.  
  48. function Timer:start()
  49.   assert(self, "Self argument is invalid")
  50.   self.thread.start()
  51. end
  52. function Timer:pause()
  53.   assert(self, "Self argument is invalid")
  54.   self.isPause = true
  55. end
  56. function Timer:unpause()
  57.   assert(self, "Self argument is invalid")
  58.   self.isPause = false
  59. end
  60.  
  61. function Timer:stop()
  62.   assert(self, "Self argument is invalid")
  63.   self.exit = true
  64. end
  65.  
  66. function Timer:kill()
  67.   assert(self, "Self argument is invalid")
  68.   self.thread.stop()
  69. end
  70.  
  71. function Timer:className()
  72.   assert(self, "Self argument is invalid")
  73.   return self.__class
  74. end
  75.  
  76. return Timer
RAW Paste Data