使用lua-vararg你可以写:
local va = require "vararg"
function bind(f, ...)
local outer_args = va(...)
local function closure (...)
return f(va.concat(outer_args, va(...)));
end
return closure;
end
bind(print, 1, 2, 3)(4,5,6)
这是纯lua实现
function packn(...)
return {n = select('#', ...), ...}
end
function unpackn(t)
return (table.unpack or unpack)(t, 1, t.n)
end
function mergen(...)
local res = {n=0}
for i = 1, select('#', ...) do
local t = select(i, ...)
for j = 1, t.n do
res.n = res.n + 1
res[res.n] = t[j]
end
end
return res
end
function bind(func, ...)
local args = packn(...)
return function (...)
return func(unpackn(mergen(args, packn(...))))
end
end
bind(print, 1, nil, 2, nil)(3, nil, 4, nil)