TriggerLogic.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. --触发事件处理模块
  2. --需要保证订阅在前, 触发在后
  3. local TriggerDefine = require("trigger.TriggerDefine")
  4. --订阅列表
  5. local moniterTbl = {}
  6. -- 注册事件
  7. -- 为每个玩家维护订阅表
  8. function SubscribeEvent(eventType, uuid, callback)
  9. if not moniterTbl[uuid] then
  10. moniterTbl[uuid] = {}
  11. end
  12. if not moniterTbl[uuid][eventType] then
  13. moniterTbl[uuid][eventType] = {}
  14. else
  15. for i, funcCallBack in ipairs(moniterTbl[uuid][eventType]) do
  16. if funcCallBack == callback then
  17. print("[SubscribeEvent] 重复订阅消息 eventType = "..eventType)
  18. return
  19. end
  20. end
  21. end
  22. table.insert(moniterTbl[uuid][eventType], callback)
  23. end
  24. -- 发布订阅
  25. function PublishEvent(eventType, uuid, nValue1, nValue2, nValue3)
  26. if moniterTbl[uuid] and moniterTbl[uuid][eventType] then
  27. for i, callback in ipairs(moniterTbl[uuid][eventType]) do
  28. --print("[PublishEvent] 触发回调 eventType = "..eventType.." i = "..i)
  29. pcall(callback, eventType, uuid, nValue1, nValue2, nValue3)
  30. end
  31. end
  32. end
  33. -- 取消订阅
  34. function UnsubscribeEvent(eventType, uuid, callback)
  35. if moniterTbl[uuid] and moniterTbl[uuid][eventType] then
  36. local tSubData = moniterTbl[uuid][eventType]
  37. for i, cb in ipairs(tSubData) do
  38. if cb == callback then
  39. table.remove(tSubData, i)
  40. break
  41. end
  42. end
  43. if nil == _G.next(tSubData) then
  44. moniterTbl[uuid][eventType] = nil
  45. end
  46. end
  47. end
  48. -- 移除所有订阅(玩家下线)
  49. function RemoveAllscribeEvent(uuid)
  50. moniterTbl[uuid] = nil
  51. end
  52. function onLogout(human)
  53. -- 这里应该先发下线事件,但是目前没有这种需要先不管
  54. RemoveAllscribeEvent(human.db._id)
  55. print("[TriggerLogic-onLogout] 玩家下线移除所有事件订阅 name = "..human.db.name)
  56. end