如果要知道handler方法的原理首先得知道lua中 "." 和 ":" 还有 "..."的用法,关于这些网上资料就多啦!都说得比较透彻,在这里就不罗嗦了。
不过为了说明还是首先贴一段测试代码:
1
2
3
4
5
6
7
8
|
self._m=
"hello"
|
当执行完这一段代码后输出的结果为:
hello
nil
看出来什么问题没?是的cls中的self变成了clsb,所以当使用cls.fun调用cls:fun时,cls.fun中的第一个参数就是cls:fun中的self。
源码:
1
2
3
4
5
|
returnfunction(...)
return
method(obj,...)
end
|
由此不难发现handler通过接收的两个参数obj, method创建了一个匿名函数并将其返回,并且调用匿名函数时所传入的参数也将传入method方法中,作为obj后面的参数。
好吧我们看看它的用法:
既然通过handler封装返回的是一个匿名函数,所以可以这样调用
1
2
3
4
5
6
|
"close"
print(self._m)
|
结果为:
close
此时我们通过handler将cls作为cls.onClose的第一个参数传入,此时执行返回的匿名函数时则等价于cls.onClose(cls)由于传入的参数就是其本身所以self就是cls也即等价于cls:onClose(),所以此代码段打印出close。
如果第一个参数不是它自己的话由上面的测试代码可以知道那样就不会是我们想要的结果了。
简单的调用会了,我们再来看一看它更复杂的用法
1
|
"hello"
,handler(cls,cls.onClose))(
"world"
)
|
这个明白是什么东西吗?好吧我看了也是一头雾水,不过我们也可以慢慢地去分析,逐渐就会明了了。
此时我们把handler(cls,cls.onClose)看成是method,则上面的代码可以转换成
1
|
"hello"
,method)(
"world"
)
|
此时通过传入参数”world”调用handler返回的匿名函数,实际调用的函数method的第一个参数为”hello”,所以它的调用可以简化为
1
|
|
此时我们再将method展开
1
|
|
同理展开为
1
|
|
同理那一长串调用的就是
1
|
|
理论结合实践,那我们就来检验一下:
1
2
3
4
5
|
print(...)
"hello"
,handler(cls,cls.onClose))(
"world"
)
|
结果为:
hello world
多么亲切的hello world呀!