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")

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?


I always make resources be referenced by userdata so I can: Know what I'm accessing in the native code side (I could use a pointer and some kind of mambo jambo to do that but that is subject to another topic) and add it to the registry and in that way creating a reference to it that the garbage collector won't touch.

Refer to Lua registry section 1

Hope this helps.

  • \$\begingroup\$ I know what the registry is, but I'm not looking to ignore garbage collection, I'm looking to leverage it. If you can explain how your solution would solve my case then I would appreciate it. \$\endgroup\$ – PatrickB Nov 20 '15 at 23:17
  • \$\begingroup\$ Integers aren't garbage collected only lua objects are. You must provide some context to it so you can acomplish what you are trying to do. \$\endgroup\$ – MrCOPYPASTE Nov 22 '15 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.