Stay Hungry,Stay Foolish!

Lua参数绑定函数实现方法

背景

对于某一个函数, 其被调用多次, 每次调用的入参都是一致的。

不想每次都填写参数, 如果能够定义一个新的函数, 将参数跟此函数绑定就棒哒哒了。

local function pirntfunc(...)
    local args = {...}

    for _,arg in pairs(args) do
        print(arg)
    end
end


pirntfunc(1, 2)
pirntfunc(1, 2)
pirntfunc(1, 2)
pirntfunc(1, 2)

-- 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(1, 2)


local function makePrintFunc(...)
    local args = {...}

    return function()
        pirntfunc(unpack(args))
    end
end

local printfuncBindedArg = makePrintFunc(4, 5)
printfuncBindedArg()

 

LOG:

>lua -e "io.stdout:setvbuf 'no'" "test.lua" 
1
2
4
5

 

posted @ 2016-11-19 00:17  lightsong  阅读(1685)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel