user2883715
user2883715

Reputation: 557

Lua C++ class binding garbage collection off

I'm currently being in a game project and have to integrate Lua into the game engine to expose interface of game object and component to script users.

I tried to research ways to bind C++ class object to Lua, and I found most documentation explains how to do it with userdata type.

Yet, our project manages game objects ourselves(which means we decides when we delete, create game objects), I wonder if I can disable garbage collection of Lua. Specifically, can I try to replace __gc in metatable to nil or function that does nothing?

My compensation was to use table that contains lightuserdata(this pointer) and static functions that retrieves 'this pointer' and calls member function with it manually. However, as programmers should make wrapper static function manually, it will be dirty and hard to manage soon.

Can I get some links to good documentation of proper use or your solution to similar problem?

Upvotes: 2

Views: 1056

Answers (2)

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

LuaBridge documentation simultaneously describes how the problem of yours can be solved, and offers an out of the box solution - LuaBridge. You don't need to roll your own. There are a couple of other binding libraries you might consider too.

Upvotes: 0

Seg Fault
Seg Fault

Reputation: 1351

If your game objects are managed by your game engine, just let your Lua userdata objects be plain pointers to your game objects, that way Lua's GC will only collect them, not the actual objects.

And if you want your objects' lifetime to be managed by both Lua and C++, you can for example use std::shared_ptrs to your objects, and have the Lua userdata also hold such a smart pointer, that way both worlds operate on the same reference counter, even if with some additional "stuff" going on in the case of the Lua-managed pointers.

Upvotes: 3

Related Questions