Heya, today I was just thinking about memory leaks and what could cause them, and for me, i quite use Random.new() alot, without setting a variable or something
But I really never thought about the fact that creating a random everytime i want to get a random child could cause memory leaks? Im assuming it does make a memory leak because im creating a new random without ever destroying it.
Random.new() returns an object with methods, and it will be treated as an metatable object. That means its’ properties will not be garbage collected unless it’s properly cleaned up as a table. So when you call the constructor, it will exist in memory until it’s properly cleaned up using table.clear() and setmetatable(myRandomVariable, nil).
Essentially, you would prevent memory leaks if you define them and re-use them, rather than creating a new object each time. However, be aware that the constructor assigns a pseudorandom seed.
You don’t actually need to manually clean it up. It’s just another normal userdatum that will garbage collect when it’s no longer referenced. Once it’s collected, the actual object it represents in the engine will be taken care of internally.
The only time userdata will cause memory leaks is if a strong reference is accidently kept, such as storing it in a table and not removing it or having a long-lasting closure keep an upvalue of it. If the only reference to it is in a local variable, you don’t have to worry about it.
That’s actually what I was just thinking about after making my post, because it wouldn’t make sense why the engineers haven’t already included a Destroy method into it / not being referenced anywhere. After thinking about the metatable metamethods for a little bit, I assumed it had a weak reference pre-defined with the constructor.
So I think your post is the actual solution, mine was more of a conjecture solely based on the documentation + theory.