首页 > 其他 > 详细

Lua 事件系统

时间:2021-08-16 22:55:07      阅读:16      评论:0      收藏:0      [点我收藏+]

要求:实现事件的监听、移除、派发

local EventSystem = {}
local this = EventSystem
this.mEventTable = {}
this.mObjTable = {}


--注册事件
function EventSystem:AddListener(eventName, handler, obj)
    
    if eventName == nil or (type(eventName) ~= ‘string‘) and (type(eventName) ~= ‘number‘) then
        print(‘EventSystem::AddListener -> eventName must be string or number‘)
    end

    if handler == nil or (type(handler) ~= ‘function‘) then
        print(‘EventSystem::AddListener -> handler must be funciton‘)
    end

    this.mObjTable[obj] = this.mObjTable[obj] or {}

    table.insert(this.mObjTable[obj], {eventName, handler})
 

    this.mEventTable[eventName] = this.mEventTable[eventName] or {}

    table.insert(this.mEventTable[eventName], handler)

end


--移除事件
function EventSystem:RemoveListener(eventName, handler)
    --print(‘EventSystem::RemoveListener‘)
    --print(eventName, handler)
    if not eventName or not this.mEventTable[eventName] then
        print(‘EventSystem::RemoveListener -> Can\‘t find eventName‘..eventName)
        return
    end

    for k, v in pairs(this.mEventTable[eventName]) do
     
        if v == handler then
           table.remove(this.mEventTable[eventName], k)
        end
    end

end


--派发消息
function EventSystem:Dispatch(event)
    print(‘EventSystem::Dispatch ‘.. event)
   
    if not event or  this.mEventTable[event] == nil then
        return
    end

    for k, v in pairs(this.mEventTable[event]) do
        v()
    end

end

-- 移除对象对应的监听
function EventSystem:RemoveObjectListeners(Obj)
    if not Obj or not this.mObjTable[Obj] then
        return
    end

    for k, v in pairs(this.mObjTable[Obj]) do
       
        EventSystem:RemoveListener(v[1], v[2])

    end

    this.mObjTable[Obj] = nil

end

return EventSystem

Lua 事件系统

原文:https://www.cnblogs.com/ZTianming/p/15149887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!