lua中handler函数的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010996533/article/details/79077450

在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())()

猜你喜欢

转载自blog.csdn.net/u010996533/article/details/79077450