views:

612

answers:

1

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.

+9  A: 

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.

Norman Ramsey