Lua尝试调用一个空方法

我无法理解为什么这段代码会导致一个错误。这一行t .__index = self不应该确保表t在Vector中查找初始化函数吗?

Vector = {}
Vector.init = function(self,x,y)
    self.x = x
    self.y = y
end
mt = {}
mt.__call = function(self,...)
    local t = {}
    t.__index = self
    setmetatable(t,self)
    t:init(...)
    return t
end
setmetatable(Vector,mt)
Vector.__add = function(self,other)
    return Vector(self.x+other.x,self.y+other.y)
end
local t = Vector(5,5)
local l = Vector(5,5)
local v = l + t
print(v.x,v.y)

我对Lua代码也不熟悉。我通常使用其他人的类库,因为我无法编写自己的。这让我感到困惑。

我已按如下方式修订了我的代码。

Vector = {}
Vector.__index = Vector
Vector.mt = {}
Vector.init = function(self,x,y)
    self.x = x
    self.y = y
end
setmetatable(Vector,Vector.mt)
Vector.mt.__call = function(self,...)
    local t = {}
    setmetatable(t,self)
    t:init(...)
    return t
end
Vector.__add = function(self,other)
    return Vector(self.x+other.x,self.y+other.y)
end
local t = Vector(5,5)
local l = Vector(5,5)
local v = l + t
print(v.x,v.y)

按预期工作

我想出了这个通用的类系统

Class = {}
Class.mt = {}
setmetatable(Class,Class.mt)
Class.mt.__call = function(self,name)
    local class = {}
    class.name = name
    class.__index = class
    class.mt = {}
    class.mt.__call = function(self,...)
        local t = {}
        setmetatable(t,self)
        t.init(t,...)
        return t
    end
    setmetatable(class,class.mt)
    return class
end
Vector = Class(“Vector”)
Vector.init = function(self,x,y)
    self.x = x
    self.y = y
end
Vector.__add = function(self,other)
    return Vector(self.x+other.x,self.y+other.y)
end

我不知道如何继承

我觉得要放弃了。我不擅长这个。

我似乎通过mixin实现了多重继承。

只需要在创建子类之前声明超级函数,否则它将无法将函数混合在一起。

Class = {}
Class.mt = {}
setmetatable(Class,Class.mt)
Class.mt.__call = function(self,name,...)
    local class = {}
    class.name = name
    class.parents = {...}
    class.__index = class
    class.mt = {}
    for k,v in pairs(class.parents) do
        for i,j in pairs(v) do
            if
                i ~= “init” and
                i ~= “parents” and
                i ~= “mt” and
                i ~= “__indexand
                i ~= “name” then class[i] = j end
        end
    end
    class.mt.__call = function(self,...)
        local t = {}
        setmetatable(t,self)
        t.init(t,...)
        return t
    end
    setmetatable(class,class.mt)
    return class
end
Vector = Class(“Vector”)
Vector.init = function(self,x,y)
    self.x = x
    self.y = y
end
Vector.__add = function(self,other)
    return Vector(self.x+other.x,self.y+other.y)
end
Vector.update = function()
    print(“从向量更新”)
end
Vector3 = Class(“Vector3”,Vector)
Vector3.init = function(self,x,y,z)
    print(“你好”)
    Vector.init(self,x,y)
    self.z = z
end
Vector3.__add = function(self,other)
    local v = Vector.__add(self,other)
    return Vector3(v.x,v.y,self.z+other.z)
end
a = Vector3(1,2,3)
a.update()
print(a.z)
点赞