Need help with OOP

I need some help with OOP… I’m a beginner at this and I need some help with it. Basically, i have a “.new” function that creates a new instance:

function bolt.new()
	
	local newbolt = {}
	newbolt.variables = {
		
		["services"] = variablesservices
		
	}
	
	setmetatable(newbolt, bolt)
	
	return newbolt
end

Then, I have this “:getservices” function that retrieves the self.variables.services from the “.new” function:

function bolt:getservices()
	
	return self.variables.services
	
end

And I also have a test script (to test the .new and :getservices functions) which is a server script:

local bolt = require(game.ReplicatedStorage:WaitForChild("Bolt").Bolt)

local newbolt = bolt.new()
print(newbolt:getservices())

Which works great but here’s the problem: The autocomplete lets me call :getservices off of both the new instance and the module itself. I dont want that. I only want to be able to call it from the new instance since this is a ressource for beginners i am working on and I dont want them to call the functions from the wrong places. Did I write something wrong? Help would be appreciated!

You can create a separate table that will store the functions like this:

local functions = {}
functions.__index = functions

function functions:getservices()
	
	return self.variables.services
	
end

Then, inside the bolt.new function, you can instead set the metatable to that functions table instead.

function bolt.new()
	
	local newbolt = {}
	newbolt.variables = {
		
		["services"] = variablesservices
		
	}
	
	setmetatable(newbolt, functions)
	
	return newbolt
end

Previously, you’re using the module to store those functions, which required a __index, so you can remove that as well.

Full code for the module script (With the current information I have):

local bolt = {}

local functions = {}
functions.__index = functions

function functions:getservices()
	
	return self.variables.services
	
end

function bolt.new()
	
	local newbolt = {}
	newbolt.variables = {
		
		["services"] = variablesservices
		
	}
	
	setmetatable(newbolt, functions)
	
	return newbolt
end

return bolt

Looking at the autocompletion tab, you’ll see that the bolt module does not contain the :getservices method, but the newbolt table does.

1 Like

Alright, thanks! I’ll make sure to test this tomorrow and I’ll mark it as the solution (:

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