Difficult situation please help. If a table references an object and I set it to nil does it get GCed?

for i,v in pairs(obj:GetDescendants()) do
--
end

The documentation tells us that a for i,v in pairs is a function by itself that you pass in a reference to a table and it creates its own variables i ,v every loop.

What I saw somewhere is that memory leaks happen when you don’t remove references properly

So in a table if u have a reference to an object and u set the table reference to nil, the table is going to exist in the memory holding a reference to that object.

Would I have to do something like this better just to be safe?

ref = obj:GetDescendants()
for i,v in pairs(ref) do
--
end
table.clear(ref)

If you are saving an Instance’s children to a variable, the table won’t just delete itself. Unfortunately if you’ve used Instance:Destroy you won’t be able to edit anything from the table because it is RobloxLocked.

no wonder memory leaks have been happening in my game

I would hope that Roblox’s garbage collection system takes account for those variables but if not check Stats:GetTotalMemoryUsageMb and find the memory usage of LuaHeap (5). You can see how much memory is truly being used.

Also give this a try from another post: How to fix a data leak - #2 by 04nv

1 Like