lua-users home
lua-l archive

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




On 15/07/16 08:05 PM, Tim Hill wrote:
On Jul 15, 2016, at 5:16 AM, Soni L. <fakedme@gmail.com> wrote:

For example, what happens when __key starts returning different values each time it is used? What happens if it returns a very restricted range of keys (and hence stresses Lua’s hash collision processing)? How are collisions avoided for __key values? Remember that __key isn’t returning a hash, it’s returning the definitive unique identifier for that userdata, and Lua assumes these are guaranteed unique for a given type (the hash need not be, of course).

—Tim

We can't have __hash because the reference manual doesn't specify how tables are implemented. For all we know, there could be a Lua table implementation that uses tries, arrays and binary search trees, instead of an array and a hashtable. __key provides a __hash-like interface without breaking such implementations.

Also, if implemented like __gc (a flag on the object), testing for __key is cheap.

I think you missed my point. The contract for a table is that each value placed in a table has a unique unchanging identity within it’s type. For a string its just the string text, for a number the number etc. For userdata its the pointer. For __key to work, it must abide by this contract. The following problems then arise:

— What is the type of the return value? It can’t be any existing Lua type, since this is *already* used as the identity of a value of that type. In other words, if __key returns (say) 100 as the key, then that will collide with using the number 100 in the same table. Not good. In fact, the only thing that __key could conceivably return would be another userdata pointer. And if you analyze this carefully, you will see if doesn’t buy you any functionality over what you already have.

Not good? If you have a bigint with value 100, any reasonable person would expect it to be compatible with a plain Lua number with value 100, just like how the plain Lua integer 100 is compatible with the plain Lua float 100.0. If Lua numbers have this property, why shouldn't other things?

— If __key returns a different value when called multiple times on the same userdata, strange things will happen, possibly including Lua crashing, since this is unexpected behavior for any Lua value. Not good.

I can crash Lua with __gc and debug.getinfo. Your point? Locking it to userdata only significantly reduces that risk.

— If two distinct userdata’s return the same type+value for __key Lua will think they are the same value and bad things will happen if they are put in the same table, possibly crashing Lua. Not good.

This won't crash Lua.

—Tim



--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.