I recently learned that game.debris and :destroy will parent a instance to nil if it still has references somewhere in any script, meaning I probably have uncountable amounts of data leaks in my games, does anybody know a way for me to sort of “browse” nil and see all of the problems so i can take them all out?
On top of that, do I even have to do this? Do things parented to nil even cause lag? The only reason I had figured this out is because in my hitbox script I have a “repeat until not part” thing that keeps running even after that part is destroyed, I can’t find any references to the part in the script and am completely lost. Do variables count as a reference? Please respond if you have any information that might help me
When something is parented to nil it’ll be eligible for garbage collection when the time is right, luau automatically will handle that for you. No need to worry about data leaks
I don’t know, but isn’t what OP said that script references to these nil’d Instances keep them from being GC’d? In that case there might still memory leaks.
From PiL:
A garbage collector can collect only what it can be sure is garbage; it cannot know what you consider garbage. A typical example is a stack, implemented with an array and an index to the top. You know that the valid part of the array goes only up to the top, but Lua does not. If you pop an element by simply decrementing the top, the object left in the array is not garbage for Lua. Similarly, any object stored in a global variable is not garbage for Lua, even if your program will never use it again. In both cases, it is up to you (i.e., your program) to assign nil to these positions so that they do not lock an otherwise free object.
- Programming in Lua : 17
So yes, that’s how I interpret it and that fits with what I’m used to.
so if a part isnt fully destroyed until there are no references, and a variable counts as a reference, then would i have to do something like part:Destroy() and also part = nil?
Nope, but if you create a centralized function for creating new instances, essentially wrapping Instance.new()
and instance:Clone()
, you can do your own counting and see if the count increases unexpectedly over time and print the name and classname of instances whose parent is nil
if you want.
Managing instantiation like this sounds a bit crazy but it’s not unheard of, e.g. it’s often used in a more limited way is how object pools work.