将函数作为参数传递,Lua。

以下问题是我的:

我想要一个能够在 Lua 中创建新对象的函数,但是应该可以扩展它。

function Class(table)
local a = {}
local t = {create = _create, __newindex = function(o,k,v)
            if k == "create" then
              --getmetatable(o).create = function()
                --_create(o)
                --v()
              --end
              -- or just create(v.params)
            else
              rawset(o,k,v)
            end
          end,
}

setmetatable(a,t)
t.__index = t
end

function _create(o,...)
return newTable
end

ele = Class:create()
function Class:create( n )
    self.name = n
end
ele2 = Class:create("bbbb")

现在 ele2 没有一个名称,但它应该创建一个新对象并将给定字符串作为名称。

我可以从 newindex 获得给定值(类型为函数)的参数吗?或者我可以执行该值吗?

点赞
用户3998938
用户3998938

有一些事情我还不确定。正如Etan所说,newTable是什么,为什么您要将create设置为Class的函数,而Class又是一个函数?

如果您想要在创建类的实例时初始化它,可以像这样做:

function Class()
    local class = {}
    class.__index = class
    return setmetatable(class, {__call = function(...)
        local instance = setmetatable({}, class)
        if instance.init then
            instance:init(select(2, ...))
        end
        return instance
    end})
end

--现在举个例子:

Dog = Class()

function Dog:init(name)
    self.name = name
end

function Dog:bark()
    print(string.format("%s barked!", self.name))
end

local pedro = Dog("Pedro")
pedro:bark() --> pedro barked!
2015-05-10 02:30:20