在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
但是,当我创建一个实例时,它却无法正常工作:
-- 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
我在做什么错了?
答案 0 :(得分:1)
坦率地说,PiL中的示例令人困惑。它描述了所谓的“原型继承”。这意味着类和对象之间没有区别。这是您的if (bstr == _bstr_t("My string"))
{
int pp = 0;
}
方法的一个版本,该版本稍微正确一些:
new
但是我们仍然有一个问题:由于我们的构造函数设置了一个实例变量,因此我们不能使用它来创建子类。如果尝试的话,这些子类都将在自己内部(而不是在其实例中)设置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)
仅用于创建实例。
答案 1 :(得分:1)
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 = {}