lua-users home
lua-l archive

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


Am 04.11.2013 21:56 schröbte 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.

You'll end up with a huge table of the same data because the pointer
of myuserdata is different (but not its content!). I usually
workaround with mytable[myuserdata:getId()] or something similar.

Maybe you could use something similar to Lua's string interning:
You need a private weak-valued table somewhere (e.g. registry or upvalue) that maps lightuserdata (the content of your shared_ptr) to full userdata (the shared_ptr object itself). Before you create a new full userdata for a shared_ptr object, you check if you can reuse an already existing full userdata which has the same content. That way you only get one full userdata for every unique shared_ptr content, and you can use it as a key in tables.

Philipp