Table Funcs

lua-users home
wiki

与看起来像函数的表相对的是看起来像表的函数。

do
  local meta = {__call = function(t, ...)
                           return t.__function(t, unpack(arg))
                         end
               }

  function Tablefunc(fn)
    return setmetatable({__function = fn}, meta)
  end
end

Tablefunc 的结果是一个具有调用语法的表,但函数有一个隐式的第一参数,即它自己的表,它可以在其中存储持久状态。

我知道你在想什么。那又怎样?这只是一个标准的无键的对象调用。如果我想要私有的持久状态呢?好的,看看 TableFuncsTwo

与此同时,这里有一个简单有趣的例子

repeater = Tablefunc(
  function(self, n, str)
    -- I've got persistent state variables
    self.times_called = (self.times_called or 0) + 1
    -- I can get at the base function and even change it
    -- so it will do something different next time
    if self.times_called >= 99 then
      self.__function =
        function() return "Sorry, I'm tired of repeating myself" end
    end
    -- I can use the table for configuration, and
    -- the functable itself is self, so I can recurse
    if n == 0 then return ""
      elseif n == 1 then return str
      else return str .. (self.delim or ", ") .. self(n - 1, str)
    end
  end)

必不可少的示例运行

$ lua
Lua 5.0 (beta)  Copyright (C) 1994-2002 Tecgraf, PUC-Rio
> -- I can get at the state variables from here, too
> repeater.delim = "; "
> print(repeater(7, "hello"))
hello; hello; hello; hello; hello; hello; hello
> print(repeater.times_called)
7
> _ = repeater(90, "hello")
> print(repeater.times_called)
97
> print(repeater(7, "hello"))
hello; hello; Sorry, I'm tired of repeating myself

--RiciLake

另一个实现
function wrap(fn)
  local t = {}
  return function(...) return fn(t, ...) end, t
end
或者这样

local states = setmetatable({}, {__mode = "kv"})
function addstate(fn)
  local t = {}
  local fn2 = function(...) return fn(t, ...) end
  states[fn2] = t
  return fn2
end
function getstate(fn)
  return states[fn]
end
--DavidManura

RecentChanges · preferences
编辑 · 历史
最后编辑于 2007 年 5 月 28 日 上午 11:15 GMT (diff)