Hello, I am trying to figure out OOP in Roblox Lua.
What I have here is a "class" named BrickModel which can spawn bricks, and a "class" named UnanchoredBrickModel which can spawn bricks differently.
local BrickModel = {} BrickModel.__index = BrickModel function BrickModel:new(color, size) local mt = setmetatable({color = color, size = size}, BrickModel) mt.__index = self return mt end function BrickModel:createInstance(positionVector3) -- code for creating a new part and returning it end local UnanchoredBrickModel = {} UnanchoredBrickModel.__index = UnanchoredBrickModel function UnanchoredBrickModel:new(color, size) local mt = setmetatable({color = color, size = size}, UnanchoredBrickModel) mt.__index = self return mt end -- There is also a separate createInstance method for UnanchoredBrickModel, this has been skipped as it is self-explanatory
Ideally I would like UnanchoredBrickModel to just extend BrickModel. I have tried doing this by doing something like this:
local UnanchoredBrickModel = BrickModel:new()
However, when I called UnanchoredBrickModel:createInstance(), it seemed to call BrickModel:createInstance() instead. My friend suggested separating the two classes, although I would like to know if it would be possible to extend BrickModel to UnanchoredBrickModel, and if so, how.
Don't quote me on any of this - I'm still getting the hang of OOP and metatables myself, but hopefully I can be of some use.
--> declare the 'base' class. local Brick = {} Brick.__index = Brick --> create the constructor for the 'base' class. function Brick.new(color, size) local self = setmetatable({}, Brick) self.__index = self self.color = color self.size = size return self end --> define methods for the 'base' class. function Brick:GetData() print(self.color, self.size) end --> declare the 'derived' class inheriting the 'base' class. local TransparentBrick = Brick.new() --> create the constructor for the 'derived' class. function TransparentBrick.new(color, size, transparency) local self = setmetatable(Brick.new(color, size), TransparentBrick) self.__index = self self.transparency = transparency return self end --> define methods for the 'derived' class. function TransparentBrick:GetData() print(self.color, self.size, self.transparency) end local brick = Brick.new('Deep orange', Vector3.new(1, 1, 1)) brick:GetData() local transparentBrick = TransparentBrick.new('Lavender', Vector3.new(2, 2, 2), 0.5) transparentBrick:GetData()