每次创建不同 class 的新对象时都会被覆盖
Creating of a new object of a different class gets overriden every time it's created
我对 OOP 还是很陌生,但我不知道我做错了什么。
-- TestModule
testClass = {}
local thingClassModule = require(script["ThingModule"])
function testClass:new()
setmetatable({}, self)
self.__index = self
self.Thing = thingClassModule:new(10, 15)
self.Thing2 = thingClassModule:new(30, 70)
end
return testClass
东西 class 模块:
-- ThingModule
thing = {}
function thing:new(a, b)
local obj = {}
setmetatable(obj, self)
self.__index = self
self.A = a or 0
self.B = b or 0
return obj
end
return thing
问题是 Thing 被 Thing2 覆盖了。
在方法中,self
是方法调用中冒号之前的任何内容。在 thing.new
中,您创建了一个名为 obj
的新 table,但您随后在 self
中分配了 A
和 B
,即 thing
table(或 thingClassModule
;它们是相同的 table)。在 testClass.new
中,您设置了新 table 的元 table,但您没有将其存储到变量中。然后你继续修改self
,就是testClass
.
我认为您的问题不是将 self
分配给对象的元表,而是将其分配给模块,因此它会覆盖数据而不是创建新对象。
这是您要实现的目标的工作示例:
-- Thing Class
local Thing = {}
Thing.__index = Thing
function Thing.new(a, b)
local self = {}
setmetatable(self, Thing)
self.A = a
self.B = b
return self
end
return Thing
local Thing = require(script.Parent.Thing)
local TestClass = {}
TestClass.__index = TestClass
function TestClass.new()
local self = {}
setmetatable(self, TestClass)
self.Thing = Thing.new(10, 15)
self.Thing2 = Thing.new(30, 70)
return self
end
return TestClass
您可以通过这篇很棒的文章了解有关面向对象的更多信息:
https://devforum.roblox.com/t/all-about-object-oriented-programming/8585
我对 OOP 还是很陌生,但我不知道我做错了什么。
-- TestModule
testClass = {}
local thingClassModule = require(script["ThingModule"])
function testClass:new()
setmetatable({}, self)
self.__index = self
self.Thing = thingClassModule:new(10, 15)
self.Thing2 = thingClassModule:new(30, 70)
end
return testClass
东西 class 模块:
-- ThingModule
thing = {}
function thing:new(a, b)
local obj = {}
setmetatable(obj, self)
self.__index = self
self.A = a or 0
self.B = b or 0
return obj
end
return thing
问题是 Thing 被 Thing2 覆盖了。
在方法中,self
是方法调用中冒号之前的任何内容。在 thing.new
中,您创建了一个名为 obj
的新 table,但您随后在 self
中分配了 A
和 B
,即 thing
table(或 thingClassModule
;它们是相同的 table)。在 testClass.new
中,您设置了新 table 的元 table,但您没有将其存储到变量中。然后你继续修改self
,就是testClass
.
我认为您的问题不是将 self
分配给对象的元表,而是将其分配给模块,因此它会覆盖数据而不是创建新对象。
这是您要实现的目标的工作示例:
-- Thing Class
local Thing = {}
Thing.__index = Thing
function Thing.new(a, b)
local self = {}
setmetatable(self, Thing)
self.A = a
self.B = b
return self
end
return Thing
local Thing = require(script.Parent.Thing)
local TestClass = {}
TestClass.__index = TestClass
function TestClass.new()
local self = {}
setmetatable(self, TestClass)
self.Thing = Thing.new(10, 15)
self.Thing2 = Thing.new(30, 70)
return self
end
return TestClass
您可以通过这篇很棒的文章了解有关面向对象的更多信息: https://devforum.roblox.com/t/all-about-object-oriented-programming/8585