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

9 篇文章 0 订阅
5 篇文章 0 订阅

其实就是用了  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, 如果里面有同名的全局函数(全局变量名) 会覆盖先加载的那个)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值