创建不同类的新对象每次都被覆盖

我还是比较新的面向对象编程, 但我无法弄清楚我在这里做错了什么.

-- 测试模块

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

Thing类模块:

-- Thing模块

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覆盖了。

点赞
用户3574628
用户3574628

在一个方法中,self 是方法调用中冒号前面的任何东西。在thing.new 中,你创建了一个名为 obj 的新表,但是你随后将 AB 分别赋值给 self 中的 thing 表(或 thingClassModule;它们是同一个表)。在 testClass.new 中,你设置了一个新表的元表,但是你没有将其存储到变量中。之后,你继续修改 self,即 testClass

2021-03-09 19:06:50
用户10730687
用户10730687

我认为你的问题不是将 self 分配给对象的元表,而是将其分配给了模块,因此它正在覆盖数据而不是创建新对象。

以下是你试图实现的工作示例:

-- Thing 类
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

2021-03-15 13:08:25