I know that the following will cause a memory leak (included fix):
--Part never gets garbage collected
do
local p = Instance.new('Part')
local dataTable = {Message = "Test"; Part = p}
p.Touched:connect(function() print(dataTable.message) end)
end
--FIX Part gets garbage collected
do
local p = Instance.new('Part')
local dataTable = {Message = "Test"; Part = p}
p.Touched:connect(function() print(dataTable.message) end)
p.Destroy()
end
This will also cause a memory leak (included fix)
--The coinTable will store every player that has ever initiated this remote event on this server
local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = replicatedStorage.RemoteEvent
local coinTable = {} --This is temporary and does not need to be saved in a datastore
local function addCoins(player)
local coins = coinTable[player.UserId]
if coins then
coins = coins + 1
coinTable[player.UserId] = coins
else
coinTable[player.UserId] = 1
--started at 1 to simulate adding a coin
end
for i,v in pairs(coinTable) do
print(i, v)
end
end
remoteEvent.OnServerEvent:Connect(addCoins)
--FIX adding this will clean up the table entry
players.PlayerRemoving:Connect(function(player)
coinsTable[player.UserId] = nil
end)
Is there anything else I'm missing that could cause a memory leak? I don't use temporary scripts and have little to no instances. If my events are permanent as well as my functions, am I good to go? Thank you

6 comments
You most likely will never have to worry about garbage collection unless you are going to dabble with OOP using module scripts. As long as you know you don't need anything ever again, set it or its parent to nil and it'll be marked for collection.
Also, you don't need to iterate through a table to set everything inside to nil, just set the entire table to nil and it'll get rid of the whole thing.
Thank you for your answer! The for loop was just so I could test to see if the player's coin value was still in memory after they left the server. I meant to add the prints to show this, but I got a little lazy.
If you paste this as an answer, I'll accept it
done
I had a similar question like this earlier this year, and if you really want to, you can read more about lua's garbage collection here: https://www.tutorialspoint.com/lua/lua_garbage_collection.htm