I’m just trying to figure out if I’m deconstructing my object correctly, is it going to clean everything up?
function AISpawner.new()
local self = {}
self.instance = _newAI()
self.timeOfSpawn = os.time()
self.linkedSpawn = nil
setmetatable(self, AISpawner)
return self
end
function AISpawner:cleanup()
for k in pairs (self) do
if typeof(k) == "Instance" then
k:Destroy()
else
k = nil
end
end
self = nil
end
Your original code sample will leak memory because you’re still holding references in the object during the cleanup. Destroy your instances then use table.clear to flush it of its indices.
function AISpawner:cleanup()
-- I don't assume you're using instances as keys...? Hopefully?
for _, obj in pairs(self) do
if typeof(obj) == "Instance" then
obj:Destroy()
end
end
table.clear(self)
setmetatable(self, nil)
end
The real issue is just Destroy()ing is needed for Instances, as you have done, and just setting the
Instance refs to nil would be a good idea. The rest is generally unnecessary, provided
you have set all external references to nil (eg. in other tables) (or all other references are weak)
the system will clean up the table.