Help With Object Inheritance in ModuleScript

I’ve got a module script for weapons. I want to have a separate object for each weapon that I can differentiate/adjust easily. Currently when I make a new weapon it doesn’t seem to be inheriting the values like it should. Further explanation in the code comments.

--ModuleScript
local Weapon = {}
Weapon.__index = Weapon

local SpawnedWeapons = {}

Weapon.Machinegun = {
	Name = "Machinegun",
	Type = "Hitscan",
	Firerate = 10,
}

Weapon.Shotgun = {
	Name = "Machinegun",
	Type = "Hitscan",
	Firerate = 10,
	Shots = 20,
}

function Weapon:new(Player)
	local newWeapon = setmetatable({}, self)--New empty table, with the metatable of the weapon passed from the server script
	newWeapon.Shots = self.Shots or 1--This fine yet when I try to print the Name I get nil
	newWeapon.Player = Player
	
	print(newWeapon.Name)--Prints nil so it's not correctly inheriting the Name value under Machinegun
	table.insert(SpawnedWeapons, newWeapon)
	
	Player.Character.Humanoid.Died:Connect(function()--This is my attempt at removing the weapons when the player dies, but doesn't seem to work right either
		--this function does get called but the SpawnedWeapons function below continues printing multiple objects when there should only be 1 at a time.
		newWeapon = nil
		SpawnedWeapons.newWeapon = nil
	end)
	
	print(SpawnedWeapons)
end

return Weapon

--Server script
local function PlayerJoinedGame(Player)
	Player:LoadCharacter()
	WeaponModule.new(WeaponModule.Machinegun,Player)
	Player.Character.Humanoid.Died:Connect(function()
		PlayerJoinedServer(Player)
	end)
end
1 Like

If you need to do object for that weapon , make this weapons as models or tools and put it into server storage, then add a string value with id of this weapon, and add a id variable in every weapon module, if you wan’t to get specific weapon then, use for loop to go through all weapons and find that with the same id as module data.

I’m trying to do object oriented programming specifically so I don’t need to do something like that but maybe I’m misunderstanding you. Currently I’m just trying to figure out why newWeapon is not inheriting the self table and how to wipe the table after when the character dies in the Humanoid.Died function

You would need to return the new weapon in Weapon.new(). And, set the metatable to Weapon, not self. The weapon table would need to have __index set to itself.

local self = {}
-- later:
return setmetatable(self, Weapon)

Sorry little confused here. Are you saying return newWeapon and then work with it in the server script that’s calling the function? Am I better off just making new tables entirely for the weapons?