Hello. I am creating a pet module, but, whenever I test, it errors from the script that I require ‘attempt to call a nil value’. Here is my code:
local Pet = {}
Pet.__index = Pet
function Pet.new(petName, petModel, playerFor)
Pet = {Name = petName, Model = petModel, Owner = playerFor}
return setmetatable({}, Pet);
end;
function Pet:Load()
local clone = self.Model:Clone();
clone.Name = self.Name;
clone.Parent = self.Owner.Character;
end;
return Pet
I do from another script:
local pet = petsModule.new("Dragon", script.Pet, player)
pet:Load()
local petsModule = require(game:GetService("ServerScriptService").Pets);
function player_Added(player)
local pet = petsModule.new("Dragon", script.Pet, player)
pet:Load()
end;
game:GetService("Players").PlayerAdded:Connect(player_Added)
-- I know this is short, I am just practicing OOP.
I’m not really super experienced with metatables. However, it could possibly be that Pet is overwritten in the function Pet.new(), as a table: {Name = petName...}. Could it be overwriting all the pre-defined functions? Try re-writing it as:
local Pet = {}
Pet.__index = Pet
function Pet.new(petName, petModel, playerFor)
local NewPet = {Name = petName, Model = petModel, Owner = playerFor}
function NewPet:Load()
local clone = self.Model:Clone();
clone.Name = self.Name;
clone.Parent = self.Owner.Character;
end;
return setmetatable({}, NewPet);
end;
I think it’s an issue with your metatable usage. Try this instead.
local Pet = {}
Pet.__index = Pet
function Pet.new(petName, petModel, playerFor)
local NewPet = {Name = petName, Model = petModel, Owner = playerFor}
setmetatable(NewPet, Pet)
return NewPet
end;
function Pet:Load()
local clone = self.Model:Clone();
clone.Name = self.Name;
clone.Parent = self.Owner.Character;
end;
return Pet
Why would you include one of the class functions inside the constructor? This would be inefficient. The use of metatables in OOP is to make creating classes possible without having to do this