Description will be added later
Last active
April 29, 2018 18:54
-
-
Save nklbdev/0c147c4516d2d90901f8ce535095bf3a to your computer and use it in GitHub Desktop.
Lua events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Subscription | |
local S = {} | |
S.__index = S | |
function S.new(previous, event, func, first_arg) | |
local self = setmetatable({}, S) | |
self._next = nil | |
self._previous = previous | |
self._is_active = true | |
self._event = event | |
self._func = func | |
self._first_arg = first_arg | |
return self | |
end | |
function S:_getNextActive() | |
if self._is_active then return self._next end | |
local s = self._previous | |
while not s._is_active do s = s._previous end | |
return s._next | |
end | |
function S:unsubscribe() | |
if self._is_active then | |
self._previous._next = self._next | |
if self._next ~= nil then | |
self._next._previous = self._previous | |
end | |
self._next = nil | |
self._is_active = false | |
self._event:_onDeactivated(self) | |
end | |
end | |
function S:notify(args) | |
if self._is_active then | |
if self._first_arg then | |
self._func(self._first_arg, unpack(args)) | |
else | |
self._func(unpack(args)) | |
end | |
end | |
end | |
-- Event | |
local E = {} | |
E.__index = E | |
function E.new() | |
local self = setmetatable({}, E) | |
self._first = S.new(nil, self, nil, false) | |
self._last = self._first | |
return self | |
end | |
function E:subscribe(func, first_arg) | |
local s = S.new(self._last, self, func, first_arg) | |
self._last._next = s | |
self._last = s | |
return s | |
end | |
function E:raise(...) | |
local s = self._first._next | |
while s do | |
s:notify(arg) | |
s = s:_getNextActive() | |
end | |
end | |
function E:_onDeactivated(sub) | |
if sub == self._last then | |
self._last = sub.previous | |
end | |
end | |
return E |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment