Garbage Collection

local Part = workspace.Part
Let’s say that Part gets destroy in the game and the variable Part is never used through out the code. Will that part get GarbageCollected? Or will it stay there. Cuz I ain’t an industry of NIL to set it to each variable I don’t use… (Sorry for the last sentence)

if I have a function that is like:

function CollectMe()
      local Part = workspace.Part
      local Number = 5
      while wait(1) do
             Number = Number - 1
             if Number <= 0 then

Will Part be collected in the second option?

If the part gets destroyed and is no longer in the workspace, It can’t be collected, I believe. :o


i mean, the loop breaks eventually so it will collect?

plus, the reference isn’t being captured as an upvalue so

1 Like

While the variable referencing the part is in scope or will enter a scope in the future (as an upvalue for example), it won’t be collected. First scenario is collected, second scenario is collected too after the loop breaks.

1 Like

I am very worry about the second option because I used OOP in my code and idk if the stuff inside of it, which all is local will get GarbageCollected I never set them to nil that’s why I ask.

In doubt, you can always check the parent of the instance and break the loop/return the function/disconnect events if it is nil.

1 Like

yeah, that’s what I do in my code to break the loop, but will that instance get GarbageCollected after everything finished?

Yes (assuming the Part is destroyed as well), if the code ends all variables go out of scope in that case.

1 Like

Last question and sorry for interrupt you again. What about a function that is in the _G Global Value? Let’s say the Second Option is in a _G variable. Will it get GarbageCollected as well? Cuz I heard rumors that some stuff don’t get collected in _G.

_G has global scope which means you must delete the entry manually or no GC will happen
Example: _G.partVariable = nil

1 Like