# Resource management with Lua integration

I have a questions about how to better implement resource management when integrating with Lua. I have an entity system that has gameplay logic done in Lua. One of the design points was that I wanted to simplify the script code as much as possible. To that end, things like sprites and sounds are generic "resource" handles (currently just integers) that are referenced, e.g.

self.image = resource("/foo/baz.png")
self.hurtSound = resource("/foo/bar.mp3")
...
play(self.hurtSound)


This works well, but I don't know when (from the native code side) it is safe to delete a resource because a Lua object could be holding on to it. I don't have "levels" where there are convenient "load/unload" points, so I'm wondering how I might safely achieve this without making the Lua code have to do anything complicated with resources. Essentially, I want garbage collection for unused resources. I'm not a Lua expert, so I'm sure there is some feature of the language that could implement such a behavior.

My requirement is that I should be able to copy handles around safely, e.g. do not need to call resource() twice to do some kind of "obvious" reference counting. Similarly, if resource() is called n times, but at least 1 reference is valid, then the resource should not be unloaded; i.e. simply because one value was __gc'd, doesn't mean that all of them should be invalidated.

The native code implements the resource cache and simply needs to be informed when it would be safe to unload something (even if it doesn't unload it immediately).

Any Lua experts ran into similar sort of situations? What did you do to solve this problem?