lua-users home
lua-l archive

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

On 04/11/13 20:56, David Demelier wrote:

Hello there,

I use a lot userdata to index tables for further usage. It's
convenient unless you use a different pointer for your userdata.

Let explain with details,

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 want to have some container in which you record the underlying pointer, so that you reuse the same full userdata for each instance which is actually the same. The stored pointer maybe different yet this is something your container should handle, i.e the ability to cast up and down the hierarchical tree.

That is, if you call a Lua function like this:

function processData(myuserdata)
     mytable[myuserdata] = "foo"

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.

To put in a nutshell:

I propose to add a __key metamethod that the Lua VM use to index a
table, this metamethods should just return any value (except nil of
course) to index a table.

And obviously, if this metamethod is not found, Lua should just use
the userdata address, as usual.

Kind regards,

There are numerous bindings which work with shared_ptr such as Luabind, Swig and dub; which to the best of my knowledge none of these libraries have such a problem.