Question: How to remove dead object from table?

Okay so I figured that if I put a bunch of gameobjects into a table, and then deleted the gameobject, the GC would make the object nil. That doesn’t appear to to be the case becuase I’m actually storing the ID I guess.

So I did some more googling and apparently there is no go.exists() but I found this code snippet.

local function does_object_exist(id)
	return pcall(function(id) go.get_position(id) end, id) == true
end

And I tried incoporating that into my code that remakes my enemy list on an enemy death, which is this

local function remove_nils(self)
	local new = {}
	for k, v in pairs(self.enemies) do
		if does_object_exist(v) then
			table.insert(new, v)
		end
	end
	self.enemies = new
end

But I’m still getting the error. :sweat_smile: Help?

The garbage collector doesn’t make things nil, it just frees up memory when you delete all references to something.

What error?

In my opinion it would be better to have your objects call a function to remove themselves from the list on final(), rather than looping through the list and checking each one.

5 Likes

It’s an error about trying to send a message to instance of an object that no longer exists. I think I may have figured out the problem with the pcheck solution. I read that go.delete doesn’t actually delete the object until after that frame. Which I’m calling the function to remove dead objects actually immediately afterwards, so that’s probably the problem, the object still exists when I call that.

Also, oh, I was wondering what final did. :smiley: That’s a good idea. So it’s like a destructor?

Yep, final() is what you want to be using here:

Like Ross suggests I would also make sure to update your list as the object is destroyed rather than use something like go.exists().

2 Likes

Thanks, I got it. :smiley:

1 Like

I also agree with this. Much better (faster and cleaner) to remove the object when it is removed. Reactive programming patterns are really encouraged in Defold.

1 Like