Skip to content

Instantly share code, notes, and snippets.

@nrk
Created March 28, 2009 13:52
Show Gist options
  • Select an option

  • Save nrk/87107 to your computer and use it in GitHub Desktop.

Select an option

Save nrk/87107 to your computer and use it in GitHub Desktop.
Events in Lua. That is, something like the multicast delegates (synchronous) of C#... well, sort of.
local _G = _G
module('Event')
local ERROR_FUN_NOT_FUNCTION = 'Wrong parameter type: must be a function'
local function is_function(fun)
if fun and _G.type(fun) == 'function' then
return true
else
return false
end
end
local function check_function(fun)
if not is_function(fun) then _G.error(ERROR_FUN_NOT_FUNCTION) end
end
local function add_subscriber(event, fun)
check_function(fun)
event.__subscribers[fun] = true
end
local function remove_subscriber(event, fun)
check_function(fun)
event.__subscribers[fun] = nil
end
local function clear_subscribers(event, fun)
event.__subscribers = {}
end
function new()
return _G.setmetatable({
__subscribers = {},
add = add_subscriber,
remove = remove_subscriber,
remove_all = clear_subscribers,
}, {
__call = function(self, ...)
for f, _ in _G.pairs(self.__subscribers) do f(...) end
end,
})
end
require 'event'
local separator = "---------------------------------------"
local my_event = Event.new()
local function say_hello(name)
print("Hello " .. name .. "!")
end
my_event:add(say_hello)
my_event:add(function(...) print("Arguments: ", ...) end)
print(separator)
my_event("NRK", true, 10)
print(separator)
my_event:remove(say_hello)
my_event("NRK", true, 10)
print(separator)
my_event:remove_all()
my_event("NRK", true, 10)
print(separator)
--[[
########### OUTPUT ###########
---------------------------------------
Hello NRK!
Arguments: NRK true 10
---------------------------------------
Arguments: NRK true 10
---------------------------------------
---------------------------------------
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment