lua-users home
lua-l archive

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

>> I would like to store objects in a set, where the set is
>> implemented by a table mapping the objects to either true
>> or nil, depending on whether they are present or not.  In
>> order for this to work, I need equal objects (according to
>> __eq) to hash to the same location in the table.

Aaron wrote:

> I can think of a couple ways to get around this. One is to make it so that equal objects
> actually are the same table... The other way is to make your own "hash" function that 
> translates equal objects to the same string and unequal objects to different strings.

Hmm. I don't really like either of these approaches. Re: the first
approach...although it might be convenient in some cases, in general,
I think it would be impossible or a severe pain (or at the very least
a minor pain! :-) to ensure that equal objects are the same table.

I don't like the second approach either. The 'stringifying' hash
function needs to be perfect, otherwise unequal elements with equal
hashes will clobber each other. Also, if the elements being stored are
collections of other objects, and equals comparison is based on what
objects are in the collection, then it's required that all contained
objects also have a tostring method that can be used to compare
objects and give the same results as __eq. Also, the 'hashes' of the
objects being stored will often be about as big as the objects
themselves, since the hash must reliably distinguish different

You could relax the requirement that the hash be perfect, if you put
objects with the same hash in a list, ensuring that the list contains
no duplicates according to equals. Maybe this is the most reasonable

I am just used to python and java, where you can define your own
hashing and equals methods for each type of object. It seems like it
would be pretty easy to add a __hash metamethod to Lua... is there any
interest in implementing this, or some reason not to?