For my game, I had to implement a custom 2D Hitbox. I chose to go the route of proxy table OOP implementation so that I don’t have to sacrifice the __newindex metamethod. However, I’m a little concerned about what I have got here (github).
I’m not worried about the details of the functions I have created but the overall structure of the Hitbox class. I would also like to know how to implement a :Destroy() method on the class that would make sure there are no memory leaks since I expect Hitboxes to be used and discarded over long gameplay sessions. I don’t want to stress the memory or crash the server/client.
Lua is a language in which memory management is controlled automatically for you. By extension, you can not deallocate memory directly. The ‘garbage collector’ in Lua will do this for you. In order for the garbage collector to clean up tables that are no longer used, simply lose reference.
Your ‘:Destroy()’ method would simply need to cause any data structure or variable which refers to that specific hitbox instance to lose reference to it. You could create a sort of ‘HitboxManager’ which centralizes and keeps track of all hitbox instances. This lets you guard initialization and destruction of your hitbox instances, helping you prevent memory leaks.