背景
对于某一个函数, 其被调用多次, 每次调用的入参都是一致的。
不想每次都填写参数, 如果能够定义一个新的函数, 将参数跟此函数绑定就棒哒哒了。
local function pirntfunc(...)
local args = {...} for _,arg in pairs(args) do
print(arg)
end
end pirntfunc(, )
pirntfunc(, )
pirntfunc(, )
pirntfunc(, ) -- can we have printFunc12, equivalent to printFunc called with 1,2
pirntfunc12()
类似javascript function.bind功能:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
function list() {
return Array.prototype.slice.call(arguments);
} var list1 = list(1, 2, 3); // [1, 2, 3] // Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(null, 37); var list2 = leadingThirtysevenList();
// [37] var list3 = leadingThirtysevenList(1, 2, 3);
// [37, 1, 2, 3]
解法
local function pirntfunc(...)
local args = {...} for _,arg in pairs(args) do
print(arg)
end
end pirntfunc(, ) local function makePrintFunc(...)
local args = {...} return function()
pirntfunc(unpack(args))
end
end local printfuncBindedArg = makePrintFunc(, )
printfuncBindedArg()
LOG:
>lua -e "io.stdout:setvbuf 'no'" "test.lua"
1
2
4
5