TriggerLogic.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. --触发事件处理模块
  2. --需要保证订阅在前, 触发在后
  3. local TriggerDefine = require("trigger.TriggerDefine")
  4. --订阅列表
  5. local moniterTbl = {}
  6. --检测触发事件是否正确
  7. local function checkTrigger(arg)
  8. local errTag = nil
  9. if type(arg) == "table" then
  10. for _, tag in ipairs(arg) do
  11. if not TriggerDefine.TRIGGERADDTB[tag] and not TriggerDefine.TRIGGERUPDATETB[tag] then
  12. errTag = tag
  13. break
  14. end
  15. end
  16. else
  17. if not TriggerDefine.TRIGGERADDTB[arg] and not TriggerDefine.TRIGGERUPDATETB[arg] then
  18. errTag = arg
  19. end
  20. end
  21. if errTag then
  22. assert(false, string.format("注册事件不存在, tag = %s", errTag))
  23. end
  24. return true
  25. end
  26. --注册订阅
  27. function RegisterMoniter(triggerArr, cbFunc)
  28. checkTrigger(triggerArr)
  29. local handler = #moniterTbl+1
  30. moniterTbl[handler] = {
  31. triggerArr = triggerArr,
  32. cbFunc = cbFunc,
  33. }
  34. return handler
  35. end
  36. --移除订阅
  37. function RemoveMoniter(handler)
  38. if not handler then
  39. return
  40. end
  41. table.remove(moniterTbl, handler)
  42. end
  43. --广播
  44. function Broadcast(human, triggerTag, val, isAdd)
  45. for tag, v in ipairs(moniterTbl) do
  46. if table.find(v.triggerArr, triggerTag) then
  47. local f = v.cbFunc
  48. local res = pcall(f, human, triggerTag, val, isAdd)
  49. if not res then
  50. print(string.format("广播失败, handler = %s", tag))
  51. end
  52. end
  53. end
  54. end
  55. --触发事件
  56. function Trigger(human, triggerTag, val)
  57. local isAdd = false
  58. if TriggerDefine.TRIGGERADDTB[triggerTag] then
  59. isAdd = true
  60. end
  61. if not isAdd then
  62. if not TriggerDefine.TRIGGERUPDATETB[triggerTag] then
  63. assert(false, string.format("触发事件不存在, tag = %s", triggerTag))
  64. end
  65. end
  66. Broadcast(human, triggerTag, val, isAdd)
  67. end