I have a player[1] memory leak somewhere in my game, and I’m guessing it’s because of something similar to this
local t=setmetatable({},{__mode='k'})
t[{}]=true
t[next(t)]={next(t)}
while next(t)do
wait()
print'in'
end
print'GCED'--never printed
The current GC doesn’t do this, but isn’t it more correct to say an object should be garbage collected iff after disconnecting all the weak references, no strong reference is reachable from a resumable thread? Maybe this is super difficult to implement, but it would be really awesome
[1] To allow for weak instance references I use
this module
--[[
WIT: Weak Instance Table
Lets weak tables use instances as weak references
https://devforum.roblox.com/t/weak-tables-dont-work-with-instances/86634
It doesn't really know when it is destroyed/gced though bc that is impossible, instead it knows if Parent is nil :/
--]]
local refs={}
local function add(ins)
refs[ins]=true
end
local function rem(ins)
refs[ins]=nil
end
for _,ins in ipairs(game:GetDescendants())do
pcall(add,ins)
end
game.DescendantAdded:connect(function(ins)
pcall(add,ins)
end)
game.DescendantRemoving:connect(function(ins)
pcall(rem,ins)
end)
return nil
If anyone wants to check if they have a player memory leak in their game, run this code in a server script in accurate play solo studio and destroy/kick/remove the player instance from the server side and see if the output ever decreases from 1 to 0
code
local t=setmetatable({},{__mode='k',})
game:GetService'Players'.PlayerAdded:Connect(function(plr)
t[plr]=true
end)
game:GetService'Players'.ChildRemoved:Connect(function(plr)
game:GetService'Debris':AddItem(plr,1)
end)
local refs={}
local function add(ins)
refs[ins]=true
end
local function rem(ins)
refs[ins]=nil
end
for _,ins in ipairs(game:GetDescendants())do
pcall(add,ins)
end
game.DescendantAdded:connect(function(ins)
pcall(add,ins)
end)
game.DescendantRemoving:connect(function(ins)
pcall(rem,ins)
end)
while wait()do
local n=0
for k,v in next,t do n=n+1 end
print(n)
end
Probably only games that use weak player references will have memory leaks, but I’m curious about this nonetheless