If you store a part in a variable and destroy the part. Does the var contain the part still?

I’ve got a script that basically has a variable that stores a part. This part is inside a model.

I later destroy the parts parent (model) using “game:GetService(“Debris”):AddItem”

Does the variable that stored the part still exist, or does the variable become nil?

Because in my case my script seems to think the part exists but it’s parent does not.

The variable would be nil.‏‏‎ ‎‏‏‎ ‎

Nope, the variable still “exist”, but the part/model parent is nil, yup.
But, if you perform a check if statement to check if the variable is not nil, script will say that variable is not nil, only the parent, causing this:

local PartVariable = game.Workspace:WaitForChild("Part")

game:GetService("Debris"):AddItem(PartVariable, 10)

while true do
	print("Variable contains:", PartVariable)
	if PartVariable then
		warn("variable is not nil")
	elseif PartVariable == nil then
		warn("variable is nil")
	end
	
	if PartVariable.Parent == nil then
		warn("BUT part was destroyed")
	end
	
	task.wait(0.5)
end
4 Likes

Hmm, I guess I gotta check if it’s parent is nil and manually set the variable to nil

Edit: or actually is there a way to check if the part is nil or not that is inside the variable?

Yup, exactly, you should turn the variable to nil, specially for garbageCollection. But, would depend on the approach… Why having static/hardcoded variables referencing objects that will be destroyed?

You probably wont even need to have a variable in script referencing that part.
As long as you feel confy, try anything that works for you, thats what I think

Like others have suggested, the variable will still hold a reference to the part object until you manually set the variable to nil or something else, in which case if the object has had :Destroy(); called on it, will allow the garbage collector to free up memory which the part was previously occupying.

Strange, I thought the GC automatically would clear this from memory at some point? So you have to manually null variables in Lua after using them?

AFAIK Roblox Instance References aren’t cleared

Yes. It would be weird if the garbage collector automatically managed your variables, that may lead to some undefined behaviour which is undesirable. It’s a good idea to set a variable referencing a destroyed part to nil for continuity’s sake and also so that the garbage collector can free up the memory.

If you read the wiki regarding :Destroy();, from memory I’m pretty sure it mentions that the memory occupied by the part will finally be cleaned up automatically by the Lua garbage collector once all references to the part within scripts have been removed.