lua-users home
lua-l archive

Re: absence of a __hash metamethod

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


Canonicalized, write-once tuples. Not that those are available...
But essentially, if you have a way to hash a table, then what you probably
want to do is:
 hashToTable = setmetatable( {}, { __mode = "v" } )
 tableWithComplexKeys = setmetatable( { },
 __index = function( t, k )
 local hash_k = hash( k )
 local kk = hashToTable[ hash_k ]
 return t[ kk ]
 -- Uses the fact that t[ nil ] will be nil
 end,
 __index = function( t, k, v )
 local hash_k = hash( k )
 local kk = hashToTable[ hash_k ]
 if kk == nil then
 hashToTable[ hash_k ] = k
 kk = k
 end
 t[ kk ] = v
 end
 }
You could also choose to index the resultant table with uniquely generated
values tied to the hashes in order to avoid problems with the values of the
keys being mutated:
 hashToTable = setmetatable( {}, { __mode = "v" } )
 tableWithComplexKeys = setmetatable( { },
 __index = function( t, k )
 local hash_k = hash( k )
 local kk = hashToTable[ hash_k ]
 return t[ kk ]
 -- Uses the fact that t[ nil ] will be nil
 end,
 __index = function( t, k, v )
 local hash_k = hash( k )
 local kk = hashToTable[ hash_k ]
 if kk == nil then
 kk = { } -- private value
 hashToTable[ hash_k ] = kk
 end
 t[ kk ] = v
 end
 }
Mark

AltStyle によって変換されたページ (->オリジナル) /