Lua 函數物件

lua-users home
wiki

本頁說明幾個實用函數,對於使用 Lua 中的函數物件有所助益。函數物件是任何可呼叫的實體,含函數與定義「function」標籤方法的物件。

[!] 版本須知:本頁程式碼為 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)


協力開發者:JohnBelmonte
最近變更 · 偏好設定
編輯 · 歷史記錄
上次編輯:2007 年 1 月 2 日 上午 3:56(GMT)(差異)