可以在Lua中模拟绑定吗? [英] Is it possible to emulate bind in Lua?
本文介绍了可以在Lua中模拟绑定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个带有一个参数的lua函数,是否可以将此参数绑定到一个固定值以获得不带参数的函数?
Given a lua function with one argument, is it possible to bind this argument to a fixed value to obtain a function without arguments?
更一般而言,如何将lua函数的某些输入参数绑定到某些值?
More generally, how do I bind certain input arguments of a lua function to certain values?
推荐答案
是的,几乎可以使用任何具有一等值功能的语言来完成此操作.
Yes, this can be done in pretty much any language that have functions as first-class values.
function f1(a)
return a+1
end
function bind(a)
return function() return f1(a) end
end
local f2 = bind(42)
print(f2())
-- 43
此特定示例适用于特定的函数和参数数量,但可以轻松扩展为采用任意函数/参数.
This particular example works with specific function and number of arguments, but can easily be extended to take arbitrary function/arguments instead.
这篇关于可以在Lua中模拟绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文