Requiring help with OOP

I have watched a few tutorials about Object Oriented Programming and did not get the hang of it but I made my attempt to code something using it and I get a few errors, I tried following the steps of a module but yet I still failed and now I get an error,


Module:

local Players = game:GetService("Players")
local FolderHandler = {}
FolderHandler.__index = FolderHandler

local function doSomething()
	print("lol")
end

function FolderHandler.New(Player: Player)
	local self = {}
	setmetatable(self, FolderHandler)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player
	
	self:CreateValue(doSomething())
	return leaderstats
end

return FolderHandler

Server:

local handler = require(game:GetService("ReplicatedStorage").ModuleScript)
local players = game.Players

players.PlayerAdded:Connect(function(player)
	local leaderstats = handler.New(player)
	leaderstats:CreateValue()
end)

this piece of code may make some of you laugh but at the very end I’m just trying to learn so if with time in their hands are able to explain to me what I did wrong I would be very thankful.

3 Likes

Quick disclaimer: I rarely ever deal with OOP, so my answer may be incorrect. Regardless:

I believe you need to actually create the CreateValue function before trying to use it, such as this:

function FolderHandler:CreateValue()
   doSomething()
end

outside of the .New thing. Otherwise, the computer is trying to access something that doesn’t exist.

I believe this is what you were trying to do with line 17, however the method you used isn’t valid.

5 Likes

what cc. @SeargentAUS said is correct you didnot define the CreateValue method
image

3 Likes

I’m assuming here you were trying to make a function that uses a previously stated local function. In this case you should try doing this instead:

function self:CreateValue()
   doSomething()
end

my next point is that you are returning a folder instead of the self object, hence you are attempting to call a function on a folder. Instead you should return self and put the leaderstats folder inside the self object. This is the fully adjusted code:

local Players = game:GetService("Players")
local FolderHandler = {}
FolderHandler.__index = FolderHandler

local function doSomething()
	print("lol")
end

function FolderHandler.New(Player: Player)
	local self = {}
	setmetatable(self, FolderHandler)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player
	
	self.leaderstats = leaderstats
	
	function self:CreateValue()
        doSomething()
    end
    
	return self
end

return FolderHandler
2 Likes

Thank you for the help appreciate it!

1 Like

Thank you so much this helped me fix the issue!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.