Am I correctly cleaning up / deconstructing this object?

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

1 Like

I think what you want is: for k,v in pairs
and …typeof(v)
and …v:Destroy()
and …self[k] = nil

self = nil
(?? On the gc end of things, just set all external references to the spawner table to nil)
(Wherever you assign variables to them.)

But I don’t have enough context as to what you’re really trying to do.

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
3 Likes

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.

1 Like