lua-users home
lua-l archive

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



I don't know about this __hash discussion, but I did have a similar situation to yours (wanting value semantics on userdata).

The way I solved it, and the only way I was able to figure out without patching, was to keep a cache of all previously given userdata, and _regive_ an earlier userdata if one with same values was requested. All this is part of proper enum handling, without patching, on Lua. Otherwise independently created enums of the same value and same family would have been treated separate. Now, there's always just one of each ever created.

This kind of is a gotcha, or at least a little bump in the Lua language.

-asko


Colin kirjoitti 15.11.2007 kello 17:56:

On Wed, Nov 14, 2007 at 02:25:34PM +0000, James Shaw wrote:
I see this was discussed a couple of years back in the thread "equals
metamethod and hash functions"
http://lua-users.org/lists/lua-l/2005-06/msg00108.html.  Some
alternatives were suggested, mostly involving string building.

I'm using tables as keys for another table, and I'm re-generating the
tables when I need the keys (I don't think there's a simple way for me
to retain references to the original keys).

Coincidence ... I am using some userdata objects as table keys, and just today stumbled over the problem that the hashing algorithm seems to use the pointer to the actual userdata, however in some cases I actually need value semantics, i.e. I want two userdata objects to be equivalent wrt.
table lookups whenever the pointees are equal...

I would guess that one of the reasons of the missing __hash meta event is that it's not that easy to design -- how do you make sure that the __hash meta event is "compatible" with the Lua hash function and the other table
internals?

One spontaneous idea: Make __hash return a lightuserdata and a number, i.e. a pointer and a size, and then let Lua use the same algorithm as it uses for
strings on the "returned" data.

This would hopefully be still faster than all the other workarounds... (And probably saner and more "compatible" than returning an "equally distributed"
size_t that is then mapped down to an actual index.)

However I don't see how to implement such a __hash meta method in Lua; this idea is geared towards my currently problematic use case: C __hash methods
for userdata objects.

Regards, Colin