lua-users home
lua-l archive

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




On 18/07/16 10:36 AM, Soni L. wrote:


On 18/07/16 06:26 AM, steve donovan wrote:
On Mon, Jul 18, 2016 at 9:16 AM, Rain Gloom <raingloom42@gmail.com> wrote:
If I may play devil's advocate: what about simply using a special data
structure for such special cases? Ie.: just implement it as a feature of a
usual table with an __index and __newindex metamethod?
Not such a devilish idea; why not indeed? That's the method which has
worked fine for us in the past

As Philipp Janda said earlier:

You want `t[bigint(3)] = x` to be equivalent to `t[3] = x`, but `bigint(3)+bigint(3)` should use custom big integer addition, *not* the built-in Lua integer addition. For `bigint("2^128")` you'll still use an interned userdata so that `t[bigint("2^128")] = 1; print(t[bigint("2^128")])` works as expected (`__key()` would just return the userdata itself in this case).

Another example would be a UTF8String where `#` returns the number of characters not bytes, but which behaves like a regular string when used as a key in a table (and preferably when compared to a regular string via `==`, but that's a different story).

If anyone's still wondering what this whole __key thing is about, the above post sums it up nicely.

An explanation of the first part is that you can't make bigint(3) return the plain integer `3`, because then bigint(3) + bigint(3) would do plain built-in Integer addition. However at the same time, you need to, otherwise t[bigint(3)] isn't equivalent to t[3]. You can't have something that's both X and not X at the same time, and __key solves that by making bigint(3) a bigint, not a built-in Lua integer, and allowing it to behave like a built-in Lua integer in indexing operations.

--
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.