lua-users home
lua-l archive

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


Sometime on 1 May 2007, Sam Roberts wrote:
>Thanks Luis, but I would like the opposite, if a == b,
>then t[a] == t[b]:
>       a = uint64(1)
> b = uint64(1) -- uint64() returns a userdata wrapping a uint64
>       t = {}
>       t[a] = 'this'
>       t[b] = 'that'
>       assert(a == b) -- this is possible using the __eq metamethod
>       -- but this is less easy to arrange:
>       assert(t[a] == t[b])
>Since all userdata are distinct keys, as far as I can tell, lua has
>user-defined "==" equivalence, but not user-defined "hash key"
>So if I want to be able to have, for example, a numeric type where
>objects are both equivalent table keys and == equivalent, I have to
>implement a userdata factory using a weak-valued table.
>Has there been any thought to a __hash() metamethod, so objects can
>express key equivalence as well as == equivalence?

I may be misunderstanding what you want, but it seems like the memoization technique described in PIL 17.1 ( for colors represented as tables would provide what you need.

By enhancing your uint64() function with a similar memoization scheme so that the same full userdata is returned each time a particular integer value is passed you get the desired property that uint64(42) always produces a reference to the same userdata and so compares equal by all measures including when used as a table key, as long as at least one instance of uint64(42) remains uncollected at least.

The color example is pure lua, but the underlying technique should be doable entirely from C in a library as long as you find a suitably persistant place to keep the table used as a memoization cache such as in an upvalue attached to the uint64() function.

Ross Berteig                     
Cheshire Engineering Corp. 
+1 626 351 5493
+1 626 351 8645 FAX