lua-users home
lua-l archive

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

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"
>  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

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