Skip to content

Instantly share code, notes, and snippets.

@ykst
Created November 27, 2012 18:47
Show Gist options
  • Save ykst/4156178 to your computer and use it in GitHub Desktop.
Save ykst/4156178 to your computer and use it in GitHub Desktop.
event machine for lua
EventMachine = {--[[static members]]}
function EventMachine:new()
local this = {
current_actor = nil,
receivers_list = {},
event_register = {}
}
local on_mt = {
__newindex = function(tbl, event_name, func)
local actor_key = tostring(this.current_actor)
this.event_register[actor_key] = this.event_register[actor_key] or {}
if this.event_register[actor_key][event_name] then
print("duplicated receiver is not allowed: " .. event_name)
return
end
this.receivers_list[event_name] = this.receivers_list[event_name] or {}
this.receivers_list[event_name][actor_key] = func
this.event_register[actor_key][event_name] = true
end
}
function this.on(actor)
this.current_actor = actor
return setmetatable({}, on_mt)
end
local emit_mt = {
__index = function(tbl, event_name)
if not this.receivers_list[event_name] then
print("no receivers for event: " .. event_name)
return function() end
end
return function(...)
for _, func in pairs(this.receivers_list[event_name]) do
func(...)
end
end
end}
function this.emit(actor)
this.current_actor = actor
return setmetatable({}, emit_mt)
end
function this.detach(actor)
local actor_key = tostring(actor)
if not this.event_register[actor_key] then
print("detaching unknown actor: " .. actor_key)
return
end
for event_name, _ in pairs(this.event_register[actor_key]) do
print("removed '" .. event_name .. "' for " .. actor_key)
this.receivers_list[event_name][actor_key] = nil
end
this.event_register[actor_key] = nil
end
return this
end
local event = EventMachine:new()
local character = {name = "foo"}
event.on(character).revive = function(...)
print(character.name .. " revives", ...)
end
event.on(character).gainHP = function(...)
print(character.name .. " gainHP", ...)
end
event.on(character).gainHP = function(...)
-- not allowed
end
local character2 = {name = "bar"}
event.on(character2).revive = function(...)
print(character2.name .. " revives", ...)
end
event.on(character2).gainHP = function(...)
print(character2.name .. " gainHP", ...)
end
local skill = {}
event.emit().revive("foo")
event.emit().foobar(1, 2, 3)
event.detach(character)
event.detach(character2)
event.detach(character)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment