Lua中的消息分发和C#实现的比较类似,使用很方便。
这个是C#的教程地址:http://www.u3d8.com/?p=1298
上代码:
LuaEvent类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
LuaEvent = class("LuaEvent"); function LuaEvent.ctor(self, eventId) self.eventId = eventId; self.observers = {}; end function LuaEvent:Dispatch(...) for _, v in pairs(self.observers) do if v.target ~= nil then v.handler(v.target, ...); else v.handler(...); end end end function LuaEvent:AddListener(target, handler) local observer = {}; observer.target = target; observer.handler = handler; table.insert(self.observers, observer); end function LuaEvent:RemoveListener(target, handler) for k, v in pairs(self.observers) do if v.target == target and v.handler == handler then self.observers[k] = nil return k end end end |
LuaEventMgr管理类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
LuaEventMgr = class("LuaEventMgr"); local events = {} function LuaEventMgr.AddListener(target, event, handler) if not event or type(event) ~= "string" then error("event parameter in addlistener function has to be string, " .. type(event) .. " not right.") end if not handler or type(handler) ~= "function" then error("handler parameter in addlistener function has to be function, " .. type(handler) .. " not right") end if not events[event] then events[event] = LuaEvent.New(event) end events[event]:AddListener(target, handler); end function LuaEventMgr.RemoveListener(target, event, handler) if event == nil then Debug.LogError("event param is nil, please check it"); return; end if not events[event] then Debug.LogWarning("remove " .. event .. " has no event.") else events[event]:RemoveListener(target, handler) end end function LuaEventMgr.Dispatch(event,...) if events[event] then events[event]:Dispatch(...) end end |
LuaEventType:
1 2 3 4 |
LuaEventType = { Test = "Test"; } |
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function UIEventController:OnAddLuaClick() LuaEventMgr.AddListener(self, LuaEventType.Test, self.OnLuaTestEvent); end function UIEventController:OnRemoveLuaClick() LuaEventMgr.RemoveListener(self, LuaEventType.Test, self.OnLuaTestEvent); end function UIEventController:OnDispatchLuaClick() LuaEventMgr.Dispatch(LuaEventType.Test, "这是发送一个Lua事件") end function UIEventController:OnLuaTestEvent(evtData) print("接收到Lua事件内容:"..evtData); end |
- 本文固定链接: http://www.u3d8.com/?p=1798
- 转载请注明: 网虫虫 在 u3d8.com 发表过