Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I extend a class successfully?

Asked by 8 years ago

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.

01local BrickModel = {}
02BrickModel.__index = BrickModel
03 
04function BrickModel:new(color, size)
05    local mt = setmetatable({color = color, size = size}, BrickModel)
06    mt.__index = self
07    return mt
08end
09 
10function BrickModel:createInstance(positionVector3)
11 
12    -- code for creating a new part and returning it
13 
14end
15 
View all 25 lines...

Ideally I would like UnanchoredBrickModel to just extend BrickModel. I have tried doing this by doing something like this:

1local 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.

1 answer

Log in to vote
0
Answered by 8 years ago
Edited 8 years ago

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.

01--> declare the 'base' class.
02local Brick = {}
03Brick.__index = Brick
04 
05--> create the constructor for the 'base' class.
06function Brick.new(color, size)
07    local self = setmetatable({}, Brick)
08 
09    self.__index = self
10    self.color = color
11    self.size = size
12 
13    return self
14end
15 
View all 43 lines...
Ad

Answer this question