Inheriting data members from superclass

I got a question about Roblox inheritance.
I am trying to get the subclass to inherit all data members from the superclass and I am doing it like this, where the superclass is NPC and the subclass is Dummy.

MODULE 1:

-- Classes
local NPC = require(script.Parent)

local Dummy = setmetatable({}, NPC)
Dummy.__index = Dummy

function Dummy.new(name: string, owner: Player, waypoint: Part): any
    local self = setmetatable(NPC.new(name, owner, waypoint), Dummy)
    
    print(self.character)
    
    --NPC.activeNPCs[self.character] = self
    return self
end

MODULE 2:

local NPC = {}
NPC.__index = NPC

function NPC.new(name: string, owner: Player, waypoint: Part): any
    local self = setmetatable({}, NPC)

    local npcData = NPCData.getNPCStats(name)
    
    self.name = name
    self.owner = owner    
    self.waypoint = waypoint
    self.health = npcData.health
    self.walkspeed = npcData.walkspeed
    self.tier = npcData.tier
    self.character = npcData.character:Clone()
    self.character:SetPrimaryPartCFrame(waypoint.CFrame)
    self.character.Parent = workspace.Troops
    self.isAttacking = false
    
    local animator: Animator = self.character.Humanoid

    local moveAnimation: Animation = Instance.new("Animation")
    moveAnimation.AnimationId = npcData.moveAnimation
    self.moveAnimation = animator:LoadAnimation(moveAnimation)

    local idleAnimation: Animation = Instance.new("Animation")
    idleAnimation.AnimationId = npcData.idleAnimation
    self.idleAnimation = animator:LoadAnimation(idleAnimation)
    
    CollectionService:AddTag(self.character, "NPC")
    CollectionService:AddTag(self.character, string.format("%s's NPC", owner.Name))
    --NPC.activeNPCs[self.character] = self

    return NPC 
end

How do I access the data members from the superclass from the subclass? When I try to do self.character inside the subclass Dummy, I get the error: ReplicatedStorage.Classes.NPC.Dummy:20: loop in gettable. I am originally a Java developer, so I am at a lost on why this is happening.

In your NPC constructor you are returning the class instead of the object, NPC instead of self.

I believe what’s happening with the error, is that because of this, inside your Dummy constructor you set the metatable of NPC to Dummy, which causes an infinite loop backwards and forwards as it tries to find the index character.

1 Like