Will this metatable function(s) cause a memory leak?

On one script:

local Superclass = require(script.Parent.Parent:WaitForChild("TreeSuperclass"))

local TreeUtility = {}
TreeUtility.__index = TreeUtility
setmetatable(TreeUtility, Superclass)

function TreeUtility.Create()
	local Tree = Superclass.Create()
	setmetatable(Tree, TreeUtility)
	
	Tree.Name = script.Name
	
	return Tree
end

Tree.Create():Sapling()

return TreeUtility

Basically this creates the metatable with all of its inherited superclass data-etc.

On the other script:

function Utility:Sapling()
	for _, Tree in Region.Trees do
		if (SaplingPosition - Tree.TrunkPosition).Magnitude < RandomObject:NextInteger(self.SaplingSparsity[1], self.SaplingSparsity[2]) then
            print"too close to another tree!"
			return false
		end
	end

    print"worked"
    table.insert(ActiveTrees, self)
end

Trees are deleted from the ActiveTrees table once they die. However, if a tree is never added to the table, i.e no reference to it is ever established, will it get garbage collected? Or do I need to create some sort of custom destroy function for it?

Here’s the module script that actually creates the metatable if it’s important:

local Utility = {}

function Utility.Create()
	local Superclass = {}
	setmetatable(Superclass, Utility)

	Superclass.Name = "Debug Tree"

    return Superclass
end

return Utility

Does using ‘setmetatable’ give it a reference? Will I run into memory problems with custom cleanup code?

If there is no reference to an object then it will be garbage collected so I don’t think you have that to worry about.

On another note though this code seems to be making unnecessary use of metatables / have an overcomplicated design.

E.g. The TreeUtility module seems to just be a factory so it can be simplified to this:

local Superclass = require(script.Parent.Parent:WaitForChild("TreeSuperclass"))

local TreeUtility = {}

function TreeUtility.Create()
	local Tree = Superclass.Create()
	setmetatable(Tree, Superclass) -- This may not even be necessary
	
	Tree.Name = script.Name
	
	return Tree
end

TreeUtility.Create():Sapling() -- Gives the same result as before

return TreeUtility

Note how there is no longer a metatable relation between TreeUtility itself and Superclass.

It would be interesting to see how you currently want the class structure to work as I reckon there’s more simplifcations that could be made.

I have a relation between treeutility and superclass because there’s a few different trees, all with their own metatable.

However I have one superclass for them all because they’re somewhat similar besides a few things like leaf size/color/wood color/etc. I removed them from the code to simplify my problem.

I appreciate the simplifying my code though, thank you. :slight_smile: