lua-users home
lua-l archive

Re: [LUA]: Cannot use userdata as table index

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


On Saturday, July 11, 2015 02:23:14 AM Борис Александров wrote:
> http://prntscr.com/7r4ecw It seems to me that lua compares table index and
> given value by address, not by _equal metamethod
> 
This is correct. Only the primitive 
Since the GetPlayer objects define a __tostring metamethod, you can convert the 
userdata to string for use as a table key.
The __equals metamethod wouldn't be useful for tables. Lua would need a __hash 
metamethod that returns a value suitable as a table key. But I wonder what 
strange things could happen if A==B is not the same as hash(A)==hash(B)?
And anyway you can roll your own table with meta-keys.
function objecthash(o)
 -- exercise for the reader: memoize keys for the lifetime of the object
 local mt = getmetatable(o)
 if mt and mt.__hash then
 return mt.__hash(o)
 end
 return o
end
__index = function(t,o)
 return getmetatable(t).__proxy[objecthash(o)]
end
__newindex = function(t,o,v)
 getmetatable(t).__proxy[objecthash(o)] = v
end
-- 
tom <telliamed@whoopdedo.org>

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