Most of the time you don't need to recreate a Destroy function - lua's garbage collection will take care of it: whenever something no longer has a reference to it, it will eventually get garbage collected (often within a few seconds). ex:
local t = {}
t = nil
wait(3)
This works regardless of what information is contained within t. In fact, lua can handle circular references, too:
local t1 = {}
local t2 = {t1}
t1[1] = t2
t1 = nil
t2 = nil
wait(3)
However, memory leaks are still possible. The easiest one is this scenario:
- You create a Part, let's call it P.
- Another script listens to P's Changed event (I believe it will need to connect it to a function that uses P, or else this example won't work)
- You destroy all references to P (but don't call
P:Destroy())
P thus cannot be garbage collected, even though you don't need it anymore.
Thus, you will need a custom Destroy function for some of your classes. Here's what you do:
- Create a Destroy function in the class
- For each thing that class initializes, clean it up if needed:
- Call :Destroy() on any created instances (and any custom classes that also have a :Destroy function)
- Call :disconnect() on any custom events (or :Destroy() on BindableEvents/etc)
- Release any custom resources that need to keep track of how many references there are to it (ex if you have an object that is distributed to multiple coroutines/scripts and needs to destroy itself only after all those scripts are done with it. In that case, you can't just call :Destroy(), since other scripts may be using it. Instead, you need to keep track of the number of references, and only when that number reaches 0 does the object call Destroy on itself).
- You do not need to clean up basic values (numbers, tables, strings, Vector3s, etc).
- If you have nothing to destroy, there's no need for a :Destroy() function, but you might want one for consistency
If the ModuleScript contains a table of values, you might want to create/call some sort of "ClearData" function that erases the table (ex in another one of your questions you had a Deck of cards. If that ModuleScript actually contained a list of Decks in existence, you might want to clear that list (in preparation for a new round/game) so that those decks can be garbage collected, allowing you to make new ones).
2 comments
Try using :remove() instead.
Can I ask what that will accomplish?