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.


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

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

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


local NPC = {}
NPC.__index = NPC

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

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

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

    local idleAnimation: Animation ="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 

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