【问题标题】:function as parameter lua函数作为参数 lua
【发布时间】:2015-07-19 19:04:21
【问题描述】:

以下问题是我的问题:

我想要一个在 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获取给定值(类型函数)的参数还是可以执行该值?

【问题讨论】:

标签: function parameters lua


【解决方案1】:

有几件事我不确定。正如 Etan 所说,newTable 是什么,当 Class 是一个函数时,为什么你试图将 create 设置为 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

--now an example:

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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-13
    • 2012-12-16
    • 1970-01-01
    • 2012-06-28
    • 2017-04-22
    • 2016-11-06
    • 2013-02-13
    • 2013-06-03
    相关资源
    最近更新 更多