Lua-理解OOP有困难
我在理解Lua中的OOP时遇到了不少困难。根据Lua中的编程,我可以非常简单地创建类,如下所示:Lua-理解OOP有困难,lua,Lua,我在理解Lua中的OOP时遇到了不少困难。根据Lua中的编程,我可以非常简单地创建类,如下所示: Class = {} function Class:new() setmetatable({}, self) self.__index = self self.a = 1 return self end function Class:incr() self.a = 2 * self.a return self end 但是,当我去创建一个实例时,它并没有像我期望的那
Class = {}
function Class:new()
setmetatable({}, self)
self.__index = self
self.a = 1
return self
end
function Class:incr()
self.a = 2 * self.a
return self
end
但是,当我去创建一个实例时,它并没有像我期望的那样工作:
-- works as expected
instance = Class:new()
instance:incr()
print(instance) --> table 0x(address)
print(instance.a) --> 2
-- it gets weird from here on
other = Class:new()
other:incr():incr()
print(other) --> table 0x(same address)
print(other.a) --> 4
print(instance.a) --> 4
我做错了什么?坦率地说,PiL中的示例令人困惑。它描述了所谓的原型遗传。这意味着类和对象之间没有区别。下面是您的
新方法的一个版本,它稍微正确一些:
function Class:new()
-- Note that self refers to the class, here. We have to return a new object.
self.__index = self
local o = {a=1}
setmetatable(o, self)
return o
end
但我们仍然有一个问题:由于我们的构造函数设置了一个实例变量,所以我们不能用它来生成子类。如果我们尝试,这些子类都将在其自身中设置a
,而不是在其实例中。我们可以定义一个init
方法,每次创建新实例时都必须调用该方法,但这将是一个难题。以下是保持类和对象分离的一种可能方法:
-- Make sure every class has an __index pointing to itself. This lets it be the
-- metatable for both instances and subclasses.
local Class = {}
Class.__index = Class
function Class:new()
local o = {a=1}
setmetatable(o, self)
return o
end
function Class:incr()
self.a = 2 * self.a
return self
end
-- To inherit, simply use Class as the metatable.
local Subclass = {}
Subclass.__index = Subclass
setmetatable(Subclass, Class)
这样,new
只用于创建实例。奇怪的部分到底是什么?@PatrickSturm也许我的措辞有点不正确,我的意思是没有创建新对象。
function Class:new()
...
return self -- self is -> Class = {}
end
other = Class:new() -- Other will get Class = {} when you call new()
instance = Class:new() -- same here
print(other) -- will print Class = {}
print(instance) -- will print Class = {}