Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua bindings to C++ and garbage collection

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.

like image 795
toastie Avatar asked Jul 12 '09 00:07

toastie


People also ask

Does Lua use garbage collection?

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.

How does Lua garbage collector work?

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.

What is Userdata Lua?

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.


1 Answers

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.

like image 154
Norman Ramsey Avatar answered Sep 28 '22 01:09

Norman Ramsey