Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- kazagistar's event reactor
- Do whatever you want with it, no rights reserved, as per WTFPL
- (http://sam.zoy.org/wtfpl/COPYING)
- The point of this program is to provide a centralized observer pattern. Events
- can be generated by hardware and software, and any "observer" function which
- is registered will be called.
- reactor:register(event, name, func): Registers a function as an event listener,
- given the event string and a unique name string to ID this function. For the
- parameters passed to the function, see the documentation of the event sender,
- but they are always passed the event and name. If you want to listen for any
- event, listen for "reactor.any", but dont overuse this, as it can lead to poor
- performance.
- reactor:unregister(event, name): Unregisters a function from an event, given
- the event and name.
- reactor:event(event, ...): Pushes an event to resolve.
- reactor:run() Starts the reactor running. Set reactor.running = false to stop
- --]]
- if not reactor then
- reactor = {}
- reactor.observer = {}
- reactor.register = function(r, event, name, func)
- if not event then
- event = "reactor.any"
- end
- if not r.observer[event] then
- r.observer[event] = {}
- end
- r.observer[event][name]=func
- end
- reactor.unregister = function(r, event, name)
- if event == nil then
- event = "reactor.any"
- end
- r:event("reactor.delete", event, name)
- end
- reactor.event = function(r, ...)
- os.queueEvent(...)
- end
- reactor.resolve = function(r, event, ...)
- local args = {...}
- if event == "reactor.delete" then
- local event, name = unpack(args)
- r.observer[event][name] = nil
- if not next(r.observer[event]) then
- r.observer[event] = nil
- end
- end
- if r.observer[event] then
- for name, func in pairs(r.observer[event]) do
- func(event, name, unpack(args))
- end
- end
- if r.observer["reactor.any"] then
- for name, func in pairs(r.observer["reactor.any"]) do
- func(event, name, unpack(args))
- end
- end
- end
- -- This utility function is stupidly useful, so I put it here
- reactor.capture = function(str, ...) return str, arg end
- -- Until the reactor.running = false, it will pull events and share em around
- reactor.run = function(r)
- r.running = true
- while r.running do
- r:resolve(coroutine.yield())
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment