lua-users home
lua-l archive

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

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.

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,

Demelier David