其实就是用了 lua 的 loadstring 功能。
1.把需要动态生成的代码拼接成为一个字符串 存放到 str里,
2. loadstring(str)
(注:loadstring 这个只是解析了代码,需要执行一下才会生效)
所以一般写成:
loadstring(str) ()
或者:
local proc = loadstring(str)
proc()
示例:自己封装一个类似宏的函数, 我这里是定义了一个 register_msg 用来处理接收到的 协议 统一打印出来。
local code = ""
local function register_msg(msgname)
code = code.."\n".."local function PrintMsg_"..msgname.."(msg)\n local decode = protobuf.decode(\"protos.rep_"..msgname.."\", msg:GetBodyInLua())\n print(\"recv msg(\"..msg.MsgType..\") "..msgname.."\")\n protobuf.print_message_s(decode)\n end\n NetProcessorRegister.RegisterProcessor(E_PROTOCOL."..msgname..", PrintMsg_"..msgname..");"
end
register_msg("E_C2S_GET_SERVER_LIST")
register_msg("E_C2S_GET_GAME_ANN")
loadstring(code)()
code 内容 相当于一个xxxx.lua文件,文件内容为
local function PrintMsg_E_C2S_GET_SERVER_LIST(msg)
local decode = protobuf.decode("protos.rep_E_C2S_GET_SERVER_LIST", msg:GetBodyInLua())
print("recv msg("..msg.MsgType..") E_C2S_GET_SERVER_LIST")
protobuf.print_message_s(decode)
end
NetProcessorRegister.RegisterProcessor(E_PROTOCOL.E_C2S_GET_SERVER_LIST, PrintMsg_E_C2S_GET_SERVER_LIST);
local function PrintMsg_E_C2S_GET_GAME_ANN(msg)
local decode = protobuf.decode("protos.rep_E_C2S_GET_GAME_ANN", msg:GetBodyInLua())
print("recv msg("..msg.MsgType..") E_C2S_GET_GAME_ANN")
protobuf.print_message_s(decode)
end
NetProcessorRegister.RegisterProcessor(E_PROTOCOL.E_C2S_GET_GAME_ANN, PrintMsg_E_C2S_GET_GAME_ANN);
执行 loadstring(code)() 后相当于 require了 xxxx.lua这个文件。
(注另一个知识点: 加载多个lua, 如果里面有同名的全局函数(全局变量名) 会覆盖先加载的那个)