Question for advanced coders ahead:
I'm writing some clean-up code for my game and have some questions about how to remove instances of objects.
My code architecture is as follows: I have a level object. The level object has (as a child so to speak) an enemiesManager object. This enemiesManager objects has a table that contains all enemies in a scene. These enemies are instances of a pseudo-OOP object - I have an enemyClass module that is required by the enemiesManager object, and the enemy instances are table created and returned by a constructor method, called like this:
enemiesManager.enemyList[index] = enemyClass.new()
Now my big question is, how to nil this object, and more specifically, can you nil an object from within it's own code.
At the moment I have a self.kill() function that removes all event listeners, cancels all timers and removes all display objects. The self.kill() function is called by the enemiesManager for every entry in the enemyList table.
So far so good. Then I have two options:
1) I add "self = nil" to the self.kill() function after removing event listeners, timers and display objects.
2) I call "enemiesManager.enemyList[index] = nil for every enemy in the list.
I would prefer method 1 because it means my objects works very "autonomously". But this does feel tricky: can you call a function that is being deleted while it's being run. Or in other words: can you delete a function (by nilling) while it's being executed? Or is nothing being deleted, but just the pointer being removed by nilling, after which the code can be garbagecollected because there is longer a pointer to the code.
And are all pointers removed when you nil from within the object, because the enemiesManager.enemyList is then still a pointer, no? In this case, there would be another option:
3) Calling nil both from within and from the enemiesManager to nil the list entries.
So, experienced Lua coders: which is best? And is it even "allowed" to nil and object from within its own code? I wrote some test code, but it's very tricky to get concrete insights, because it's very hard to tell if tiny tiny differences in memory use (and yes, I create 1000s of objects to scale up my results) are caused by my code or by the way garbagecollecting works.
Sheesh. I'm getting confused just writing about this!