Writing of Lua event message
Summary
Recently we've been learning about Xlua's integration with projects. Here's what we need time for
Listen for event messages, trigger event messages, remove event messages, and need to be able to pass values to listening methods when listening and triggering
Realization
Write a basic method of creating classes to create objects for event messages
function simpleclass() local class_type = {} class_type.new = function() local self = {} setmetatable( self , {__index = class_type}) return self end return class_type end
Create event message object
require("simpleclass") local EventMessage = simpleclass() function EventMessage:Create() local obj = EventMessage:new() obj.data = {} return obj end
Add monitoring
--[[ self.data Loaded with event information table //structural analysis data [Event Name]= { callback callback enable Is Callback Activated attachParam Callback Arguments } ]] function EventMessage:AddNotify(event_name, callback, attachParam) if (event_name == nil or callback == nil or type(callback) ~= "function" or type(event_name) ~= "string") then __LogError("AddNotify error.param invaild") return end if (self.data[event_name] == nil) then self.data[event_name] = {} end for i,v in ipairs(self.data[event_name]) do if (v.callback == callback) then if (v.enable == false) then v.enable = true v.attachParam = attachParam else __LogError("AddNotify error.repeat added. "..event_name) end return end end table.insert(self.data[event_name], {callback = callback, attachParam = attachParam, enable = true}) end
Removing listening does not delete, it just disables
function EventMessage:RemoveNotify(event_name, callback) if (event_name == nil or callback == nil or type(callback) ~= "function" or type(event_name) ~= "string") then __LogError("RemoveNotify error.param invalid.") return end if (self.data[event_name] == nil) then return end for i,v in ipairs(self.data[event_name]) do if (v.callback == callback) then v.enable = false return end end end
Message Trigger
function EventMessage:Notify(event_name, value) if event_name ==nil or (self.data[event_name] == nil) then return end local flag = true for i,v in ipairs(self.data[event_name]) do if (v.enable == true) then v.callback(value, v.attachParam) else flag = false end end if (flag == false) then for i,v in ipairs(self.data[event_name]) do if (v.enable == false) then table.remove(self.data[event_name], i) end end end end
Use
Monitor: local function Refsh(val,self) print("Now the status is"..val) end function AddNotify() __EventMessage:AddNotify("StartGame", Refsh,self) end //remove function RemoveNotify() __EventMessage:RemoveNotify("StartGame", Refsh) end //trigger local function Start() __EventMessage:Notify("StartGame", "Start the game") end