Lua 使表可调用

示例

有一个称为的元方法__call,它定义了对象用作功能时的行为,例如object()。这可以用来创建函数对象:

-- create the metatable with a __call metamethod
local meta = {
    __call = function(self)
       self.i=self.i+ 1
    end,
    -- to view the results
    __tostring = function(self)
        return tostring(self.i)
    end
}

function new_counter(start)
    local self = { i = start }
    setmetatable(self, meta)
    return self
end

-- create a counter
local c = new_counter(1)
print(c) --> 1
-- call -> count up
c()
print(c) --> 2

元方法与相应的对象一起调用,所有其余参数在此之后传递给函数:

local meta = {
    __call = function(self, ...)
        print(self.prepend, ...)
    end
}

local self = { prepend = "printer:" }
setmetatable(self, meta)

self("foo", "bar", "baz")