https://blog.csdn.net/luoyikun/article/details/121219422
目前尚未了解到这种绑定的好处是什么。
绑定的代码如下:
-- 闭包绑定
function Bind(self, func, ...)
assert(self == nil or type(self) == "table")
assert(func ~= nil and type(func) == "function")
local params = nil
if self == nil then
params = SafePack(...)
else
params = SafePack(self, ...)
end
return function(...)
local args = ConcatSafePack(params, SafePack(...))
func(SafeUnpack(args))
end
end
-- 回调绑定
-- 重载形式:
-- 1、成员函数、私有函数绑定:BindCallback(obj, callback, ...)
-- 2、闭包绑定:BindCallback(callback, ...)
function BindCallback(...)
local bindFunc = nil
local params = SafePack(...)
assert(params.n >= 1, "BindCallback : error params count!")
if type(params[1]) == "table" and type(params[2]) == "function" then
bindFunc = Bind(...)
elseif type(params[1]) == "function" then
bindFunc = Bind(nil, ...)
else
error("BindCallback : error params list!")
end
return bindFunc
end
测试举例:
local func = function(a, b, c)
print("hello")
print(a)
print(b)
print(c)
end
if callback == nil then
print("create callback")
callback = BindCallback(func,1,2,3)
end
callback()