lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi David,

Am 04.11.2013 21:56, schrieb David Demelier:
I often use the C++11 class std::shared_ptr<> template class to push
to Lua objects and it's great because it handles reference counting,
that is if the host does not own the ressource, Lua will delete it
later with the __gc. But the drawback, is that you usually push a new
shared_ptr<> instance with the same underlying object, thus the
pointer of the userdata is different but not its content.

We too use a shared pointer implementation as the instances that are bound to userdata. As you said, they beautifully decouple both the C++ and the Lua code from concerns about the lifetimes of the object pointed to.

However, even with shared pointers, you *still* have to check the identity of the object (by looking at the raw pointer value of the shared pointer) when it is (re-)bound to Lua, and use that with a table with light userdata, for mapping to the Lua instance of the full userdata (the shared pointer), just as described in chapter 29.5, page 301 of the PiL3 book. In other words: Only a single shared pointer instance is ever needed on the Lua side (Lua then copies references to that userdata, not the userdata (shared pointer) itself), whereas on C++, you can have arbitrarily many copies.

(For completeness, using shared pointers is not the perfect solution as well, see http://thread.gmane.org/gmane.comp.lang.lua.general/92550, for which I wished there was a more straightforward solution...)

Best regards,
Carsten


--
Dipl.-Inf. Carsten Fuchs

Carsten Fuchs Software
Industriegebiet 3, c/o Rofu, 55768 Hoppstädten-Weiersbach, Germany
Internet: http://www.cafu.de | E-Mail: info@cafu.de

Cafu - the open-source game and graphics engine for multiplayer 3D action