Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- This API is meant to provide a simple but powerfull CoroutineManager which can be used as replacement of the
- ]]
- local currentRoutine = 0;
- local childEnv = {
- __index = _G;
- isCoroutine = true;
- requestCoroutineID = function()
- return currentRoutine
- end;
- }
- local masterEnv = {
- }
- childEnv = setmetatable(childEnv,childEnv)
- local CoroutineManagerTemplate = {
- currentRoutines = {};
- activeRoutines = {};
- currentFilter = {};
- masterRoutine = nil;
- isRunning = false;
- firstRun = false;
- lastEvent = {};
- addCoroutine = function(self,func)
- self.currentRoutines[(#self.currentRoutines+1) or 1] = coroutine.create(func)
- self.activeRoutines[#self.currentRoutines] = true
- return #self.currentRoutines
- end;
- removeRoutine = function(id)
- currentRoutines[id] = nil
- end;
- addActiveRoutine = function(id)
- activeRoutines[id] = true
- end;
- removeActiveRoutine = function(id)
- activeRoutines[id] = false
- end;
- run = function(self,obj)
- self.isRunning = true
- self.firstRun = true
- while self.isRunning do
- local event = {}
- self.lastEvent = event
- if not self.firstRun then
- coroutine.resume(self.masterRoutine,unpack(event))
- end
- if self.firstRun then
- local _,filter = coroutine.resume(self.masterRoutine, unpack(event))
- if(filter == "ManagerObject") then
- coroutine.resume(self.masterRoutine, self)
- end
- self.firstRun = false
- end
- if coroutine.status(self.masterRoutine) == "dead" then
- self.isRunning = false
- error("Master routine died!",0)
- end
- for k,v in pairs(self.currentRoutines) do
- if(self.activeRoutines[k]) then
- if self.currentFilter[k] == nil or self.currentFilter[k] == event[1] or event[1] == "terminated" then
- local _, filter = coroutine.resume(v,unpack(event))
- self.currentFilter[k] = filter
- end
- end
- end
- local event = {coroutine.yield()}
- end
- end;
- pause = function(self)
- self.isRunning = false
- end;
- setMasterRoutine = function(self,func)
- func = func
- self.masterRoutine = coroutine.create(func)
- return self
- end;
- }
- function new(func)
- obj = CoroutineManagerTemplate
- if func then
- obj.setMasterRoutine(func)
- end
- return obj
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement