Lua Functors

lua-users home
wiki

本页面介绍了一些在 Lua 中处理functors时非常有用的实用函数。Functor 是任何可调用的实体,这包括函数以及定义了“function”元方法的对象。

[!] VersionNotice: 本页面的代码是 Lua 4.0 版本,与 Lua 5 不兼容。

将参数值绑定到 functor 上通常很有用。[解释]

-- 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

functors 的链式调用也很有用。[解释]

-- 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)


贡献者: JohnBelmonte
RecentChanges · preferences
编辑 · 历史
最后编辑于 2007 年 1 月 1 日下午 9:56 GMT (差异)