Lua 函子 |
|
[!] 版本说明: 此页面上的代码是 Lua 4.0,与 Lua 5 不兼容。
将参数值绑定到函子通常很有用。[解释]
-- Bind - given functor and set of arguments, generate binding as new functor -- function Bind(functor, ...) local bound_args = arg return function(...) local all_args = { } AppendList(all_args, %bound_args) AppendList(all_args, arg) return call(%functor, all_args) end end -- BindFromSecond -- -- This version skips the first argument when binding. -- It's useful for object method functors when you want to leave the object -- argument unbound. -- function BindFromSecond(functor, ...) local bound_args = arg return function(...) local all_args = { arg[1] } AppendList(all_args, %bound_args) AppendList(all_args, arg, 2, -1) return call(%functor, all_args) end end
函子的链式调用也很有用。[解释]
-- Chain - generate functor that is chain of input functors -- -- Return value of output functor is result of last input functor in chain. -- function Chain(...) local funs = arg local num_funs = getn(funs) return function(...) local result for i=1, %num_funs do result = call(%funs[i], arg) end return result end end
以下是一些测试,展示了上述接口的使用以及预期输出。
function a(n, s) print("a("..n..", "..s..")") end function b(n, s) print("b("..n..", "..s..")") end MyClass = { } function MyClass.test(self, n, s) print("MyClass.test("..n..", "..s..")") end c = Bind(a, 5) d = Bind(a, 10, "ten") e = BindFromSecond(MyClass.test, 123) f = Chain(a, b, a) c("five") --> "a(5, five)" d() --> "a(10, ten)" -- assuming obj is an instance of MyClass e(obj, "abc") --> "MyClass.test(123, abc)" f(66, "chain") --> "a(66, chain)" --> "b(66, chain)" --> "a(66, chain)"
由于有一个号召创建“stdlua”库的呼声,我认为现在是时候完成这些函数的实现。有一个依赖项(AppendList
)没有显示。我相信该库会创建一些比我现有的更好的列表实用程序。无论如何,原型如下。--JohnBelmonte
-- AppendList - add items in list b to end of list a -- -- Optional closed range [from, to] may be provided for list b. Negative -- index counts from end of table. -- function util.AppendList(ta, tb, from, to)