Advertisement
HDeffo

Daemon

Aug 10th, 2018
461
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. --a stateless iterator for use in for loops.
  2. local function fIter (t, i)
  3.     i = not i and #t or (i - 1)
  4.     if i>0 then
  5.         return i, t[i]
  6.     end
  7. end
  8.  
  9. --[[a table that stores all running daemons
  10. when we add a new value we first create a coroutine using the fFunc passed]]
  11. local tBackground = setmetatable({},{
  12.     __newindex = function(t, k, v)
  13.         v.cRoutine=coroutine.create(v[1])
  14.         rawset(t, k, v)
  15.     end;
  16. })
  17.  
  18. --[[starts a new daemon
  19.  
  20. fFunc = function that runs in background
  21. fError = function ran if fFunc ever ends for any reason
  22.  
  23. returns identifier for new daemon
  24. ]]
  25. function add(fFunc, fError)
  26.     tBackground[#tBackground + 1] = {fFunc, fError=fError}
  27.     return tBackground[#tBackground]
  28. end
  29.  
  30. --[[removes a running daemon
  31. internally this sets a flag telling the system to remove this daemon next time it loops through
  32.  
  33. cRoutine = daemon to remove
  34. ]]
  35. function rem(cRoutine)
  36.     cRoutine.sFilter="Daemon_internal_remove"
  37. end
  38.  
  39. --returns identifiers for all running daemons
  40. function getBackground()
  41.     return tBackground
  42. end
  43.  
  44. --[[internal variable
  45. determines what level of depth we are in the daemon]]
  46. local bPullMeta = false
  47.  
  48.  
  49. --[[replacing the native os.pullEventRaw to function]]
  50. function os.pullEventRaw(sEvent)
  51.     local tData
  52.  
  53.     if bPullMeta then
  54.         return coroutine.yield(sEvent)
  55.     else
  56.         repeat
  57.             bPullMeta = true
  58.             tData = {coroutine.yield()}
  59.  
  60.             for iIndex, cRoutine in fIter, tBackground do --
  61.                 if cRoutine.sFilter==tData[1] or not cRoutine.sFilter then
  62.                     local bOk, sInnerEvent = coroutine.resume(cRoutine.cRoutine, unpack(tData))
  63.                     if bOk then
  64.                         cRoutine.sFilter = sInnerEvent
  65.                     else
  66.                         table.remove(tBackground, iIndex)
  67.                         if cRoutine.fError then
  68.                             cRoutine.fError(sInnerEvent, cRoutine)
  69.                         end
  70.                     end
  71.                 elseif cRoutine.sFilter=="Daemon_internal_remove" then
  72.                     table.remove(tBackground, iIndex)
  73.                 end
  74.             end
  75.             bPullMeta = false
  76.         until tData[1] == sEvent or not sEvent
  77.         return unpack(tData)
  78.     end
  79. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement