Hilariously, we’re all wrong. @DasKairo @egginabox0
So the coroutine isn’t actually treated as its own thread. It’s still part of the thread it was generated in. So although the coroutine was running parallel to the current thread, when the current thread is killed (in this case, script destroyed), the coroutine is killed too.
Unsurprisingly, we see the same results for the script connection. When the thread dies, it does too.
And then, in the middle of typing this reply, I realized this proves nothing. We’ve already discussed and agreed on that.
OKAY FINE ILL CHECK THE MEMORY USAGE BEFORE AND AFTER I DISCONNECT THE SIGNAL
After all, this will be the ACTUAL test of whether or not only using :Disconnect() is a memory leak.
Oopsies, it is. Here’s how I think that.
First, I compared the typical LuaHeap memory usage while not doing anything. It consistently hovered around 234-240 MB after a minute. Next, it’s time to blow that number up like a balloon.
Using a MouseClick event from a clickdetector, I crammed about 3.5 million instances into a table over the course of a minute, causing the LuaHeap memory usage to steadily increase from the range listed above to about 300-310 MB. After 60 seconds, the script signal would be disconnected, where the ONLY reference to the table was wrapped in. Here’s what I did:
After 60 seconds, when the disconnection occurred, the memory usage did not decrease below the inflated range, staying at around 300-310 MB.
Alright, boys. That confirms it. The thread wasn’t GC’d as would be expected. Now let me try setting con to nil.
…And imagine my shock when setting con = nil after disconnecting didn’t clear the memory. It stayed at around 300-310 MB. I tried setting the table to nil too, and I got the same result.
What??? The memory isn’t being cleared at all, regardless of what I do? Am I doing this badly or implementing it wrong? Running Destroy on the part I was clicking and the script as well didn’t free the memory either. Did I just discover an engine bug while trying to win an argument on DevForums?
Tl;dr: Your code is cursed no matter what you do. Luau is god and it is not a merciful one.