Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --a stateless iterator for use in for loops.
- local function fIter (t, i)
- i = not i and #t or (i - 1)
- if i>0 then
- return i, t[i]
- end
- end
- --[[a table that stores all running daemons
- when we add a new value we first create a coroutine using the fFunc passed]]
- local tBackground = setmetatable({},{
- __newindex = function(t, k, v)
- v.cRoutine=coroutine.create(v[1])
- rawset(t, k, v)
- end;
- })
- --[[starts a new daemon
- fFunc = function that runs in background
- fError = function ran if fFunc ever ends for any reason
- returns identifier for new daemon
- ]]
- function add(fFunc, fError)
- tBackground[#tBackground + 1] = {fFunc, fError=fError}
- return tBackground[#tBackground]
- end
- --[[removes a running daemon
- internally this sets a flag telling the system to remove this daemon next time it loops through
- cRoutine = daemon to remove
- ]]
- function rem(cRoutine)
- cRoutine.sFilter="Daemon_internal_remove"
- end
- --returns identifiers for all running daemons
- function getBackground()
- return tBackground
- end
- --[[internal variable
- determines what level of depth we are in the daemon]]
- local bPullMeta = false
- --[[replacing the native os.pullEventRaw to function]]
- function os.pullEventRaw(sEvent)
- local tData
- if bPullMeta then
- return coroutine.yield(sEvent)
- else
- repeat
- bPullMeta = true
- tData = {coroutine.yield()}
- for iIndex, cRoutine in fIter, tBackground do --
- if cRoutine.sFilter==tData[1] or not cRoutine.sFilter then
- local bOk, sInnerEvent = coroutine.resume(cRoutine.cRoutine, unpack(tData))
- if bOk then
- cRoutine.sFilter = sInnerEvent
- else
- table.remove(tBackground, iIndex)
- if cRoutine.fError then
- cRoutine.fError(sInnerEvent, cRoutine)
- end
- end
- elseif cRoutine.sFilter=="Daemon_internal_remove" then
- table.remove(tBackground, iIndex)
- end
- end
- bPullMeta = false
- until tData[1] == sEvent or not sEvent
- return unpack(tData)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement