lua中handler函数的理解

在lua,封装了一个hanlder的函数,之前对它一知半解,现在记录下

源码如下:


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

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

我们来测试一下:

local test = test or {}

function test:onTouch()
print "test in onTouch"
end

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

-- print(handler(test,test.onTouch))
-- print(test.onTouch(test))

--输出
-- function: 0086c9c8
-- test in onTouch

print( handler(test,test. onTouch))
print(( function()test. onTouch(test) end))

--输出
-- function: 0054cd40
-- function: 0054cda0

结论:
handler只不过是对method进行封装 套了一层匿名function并返回该匿名方法
所以handler(test,test.onTouch)()等价于test:onTouch()等价于test.onTouch(test)也同样等价于(function()test.onTouch(test)end())()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值