Handling Memory Leaks?

Hi,

So I’m wondering If its Possible to Handle or at Least help Prevent Memory Leaks?
I so, How should I be doing it?

1 Like

I’ve never worked with a game with an overflow of memory but I would advise trying your best to stay away from unneeded while loops or excess amount of terrain

1 Like

As far as I understand, its not about using or not any kind of loop, its about not letting resources to be freed when are not needed anymore.

Could happen a lot when using a loop:

while true do
   local thing = 5
   thing = thing + 5
   print(thing)
   task.wait()
end

In this case a variable is created each time the loop repeats, and its never set to nil, so it will stay in memory, causing a memory leak. The more it repeats the more useless memory that is stacked

while true do
  local thing = 5
  thing = thing + 5
  print(thing)
  task.wait()
  thing = nil  -- Set thing to nil to free up memory
end

The impact of just one variable holding an integer value its pretty low, idk 4 bytes? So if a loop could repeat 20 times per second, during an hour, maybe could be something like 0.288 MB?

Such measures are redundant because of Lua’s garbage collection system. It will detect elements in the stack–like objects–that are no longer being used, and it will subsequently dispose of it.
This post: A Beginner's Guide to Lua Garbage Collection explains it in detail.

Back to OP’s question, I would suggest to keep track of events that you establish. For example, if you use workspace.ChildAdded:connect(func), make sure to call :Disconnect() on this event if you know you are not going to use it later on.