Using instances as keys in a table

This might be a question with a straightforward answer, but when using instances as keys in a dictionary, do we always have to manually set it to nil when it is destroyed? If we didn’t do the following,

local dictionary = {}

workspace.DescendantRemoving:Connect(function(instance)
    dictionary[instance] = nil
end)

would there be a memory leak even though the instance is destroyed and is there another method that is shorter? Also, what happens when a local variable in a function is set to an instance that is later destroyed? I know that using Destroy() on an instance doesn’t clear references to it, but I would like to be corrected.

2 Likes

I recommend you look into the nature of weak tables, which have the unique property of removing references by choice of their key, value, or either being nil.
Answering your question, your dictionary was set up on default to contain strong keys and values, as said by the page I linked up there, and Instances do not become nil when destroyed, so your reference in the table will never be deleted until you make the reference to the instance you destroyed nil as well.

10 Likes

What I Do


Set the Instance.Name as the key while using Instance as the value that holds the key. When the Instance is removed, remove the reference through the name of the Instance.Name. However, this does not work well with multiple objects with the same name.

Setting instance’s parent to nil is equivalent to the :Destroy() function. When unused, the memory is then cleared up by collectgarbage()(?). The instance is still in the key and therefore you have to set the key’s value to nil, in order to clear it.

3 Likes

Alright, I assumed that they would be eventually removed because the Saving Player Data example on the developer hub didn’t set the player’s session data to nil after saving it. Weak tables look interesting, thanks for telling me about them.

`

Depends. If you have connections or something that references the instance, you’ve got a memory leak.

Destroy disconnects prepares instances to be garbage collected by disconnecting connections and setting an instance’s parent to nil. So long as you lose all your references, you’re fine.

Function exposed to developers to interface with the garbage collector and force it to perform an operation, not the actual thing.

2 Likes