Garbage collection on new instances of a class?

Hey developers, quick question.

Suppose I have a “while” loop that contains a “pcall”. Inside the pcall I create a new instance of a class. If an error occurs after creating this new instance, but the error is caught by the pcall (allowing the loop to continue), will the new instance of the class be garbage collected?

Here is an example of what I’m talking about:

local myClass = require(classReference)


while true do
	success, err = pcall(function()
		local newInstance = myClass.new()
		task.wait(1)
		
		--Lets say I error here before im able to erase my instance--
		
		newInstance:CleanUp()
		
	end)
	
	if err then
		warn(err)
		continue
	end
end
2 Likes

Well the error stops the thread, so in theory the instance never gets cleaned up and causes memory leaks.

1 Like

But isn’t there only one reference to that new instance meaning it would be garbage collected?

1 Like

that doesn’t guarantee that all the components in your instance gets garbage collected

1 Like

Wait then how can I be sure what does and what doesn’t…

1 Like

just ensure your instance gets deleted properly

1 Like

Fair but what would be the difference if I had just a regular variable be defined and the thread stopped versus an instance of a class. Because in theory aren’t they both only referenced inside of the enclosed loop?

1 Like

Ok I see, since they are local, there’s no external references hence it should all be garbage collected when the thread gets terminated.

2 Likes

Ohh ok, thanks for clearing that up :sweat_smile:.

1 Like