cocos2d-x Lua 中的公共函数 handler

handler函数的主要作用是将lua对象及方法包装为一个匿名函数,用来做回调函数。

许多功能都需要传入一个 Lua 函数做参数,然后在特定事件发生时就会调用传入的函数。例如触摸事件、帧事件等等。

在解释handler函数的原理之前,首先需要了解lua中 "." 和 ":" 还有 "..."的用法。

handler函数定义的位置 /src/cocos/cocos2d/functions.lua。

函数定义源码:

--[[
@param obj lua对象
@param function method 对象方法
--]]
function handler(obj, method)
    return function(...)
        return method(obj, ...)
    end
end

由此不难发现handler通过接收的两个参数obj, method创建了一个匿名函数并将其返回,并且调用匿名函数时所传入的参数也将传入method方法中,作为obj后面的参数。

以下两段代码的对比显示了handler函数的作用。

local cls = {}

function cls:test()
	self._m = "hello world"
end

local clsb = {}

cls.test(clsb)

print(clsb._m)
print(cls._m)

--[[
上述代码输出结果:
hello world
nil
--]]
是的,没有看错,cls中的self变成了clsb。

我们再运行如下代码:

function handler(obj, method)
	return function(...)
		return method(obj, ...)
	end
end

local cls = {}

function cls:test()
	self._m = "hello world"
end

local clsb = {}

--cls.test(clsb)
handler(cls, cls.test)()  -- 等同于 cls.test(cls)

print(clsb._m)
print(cls._m)

--[[
上述代码输出结果:
nil
hello world
--]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值