lua里实现类似宏定义,动态生成代码

其实就是用了  lua 的 loadstring 功能。


1.把需要动态生成的代码拼接成为一个字符串。 str

2. loadstring(str)  

这个只是解析了代码,相当于一个function   需要 执行一下才会生效


所以一般写成  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 其实类似这样一段代码

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);



理解时要注意:

1

loadstring(code) 执行后 

 NetProcessorRegister.RegisterProcessor(E_PROTOCOL.E_C2S_GET_SERVER_LIST, PrintMsg_E_C2S_GET_SERVER_LIST);
外面这个语句并不会执行
loadstring(code)()   如果是这样执行了  这句代码会被走到

但是 里面的函数 
PrintMsg_E_C2S_GET_SERVER_LIST 并不会执行的哈,不要以为会执行函数。




2. 如果里面的函数定义的是全局函数, 名字和其他地方名字一样 会覆盖原来的函数吧。   相当远 require 了一个lua文件进来  这么理解就应该能明白了。


 
 
 
 
 
 

1

猜你喜欢

转载自blog.csdn.net/zhenmu/article/details/56881268