Ok, here's a problem I'm having.
I have Lua bindings to a rendering engine that has an internal render manager that keeps its own track of pointers for the render scene and manages them. The problem is that when I'm using it from Lua, if i don't keep a Lua reference to every single object i add to the C++ render manager, it starts to garbage collect the pointers and of course cause things to crash. I don't particularly want to have to save every single reference to every single thing i create. Is there a way to force Lua to not garbage collect certain things? Are there any other ways I can get around this problem?
I'm generating the Lua bindings with SWIG.
Lua does automatic memory management. A program only creates objects (tables, functions, etc.); there is no function to delete objects. Lua automatically deletes objects that become garbage, using garbage collection.
Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program. All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management.
A userdata value is a pointer to a block of raw memory. There are two kinds of userdata: full userdata, where the block of memory is managed by Lua, and light userdata, where the block of memory is managed by the host. Userdata has no predefined operations in Lua, except assignment and identity test.
A simple way to prevent Lua from garbage collecting an object is to put that object into a table (call it uncollectable
) and then to put that table into the Lua registry.
Your other option is to use an extra level of indirection with every Lua object, i.e., use "light userdata". The light userdata points to a pointer to the C++ object, and even if the light userdata is collected, the underlying object remains unscathed.
These explanations are pretty terse, but I hope with the help of Programming in Lua, you can turn one into working code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With