[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Object equality
- From: RLake@...
- Date: Tue, 2 Jul 2002 15:22:40 +0100
OK, here are three scenarios (not complete programs). I'm still a bit
jet-lagged, so I'm not going to try to write polished code.
1) Test for table member.
In Lua, the only way to tell if a key is in a table is:
if table[key] == nil then ...
With an "equals" tag method, there is no guarantee that a value will not
compare equal to nil (unless there is such a guarantee, but that would be
yet another kludge). So the above test would need to be written:
if rawequals(table[key], nil) then ...
which is ugly, hard to read, and slow.
Note: obviously having an object compare equal to nil is a Bad Idea. But it
is certainly conceivable that someone will do it. If I'm writing a general
subroutine library, I don't want it to fail in that particular case,
however dumb I might think it is.
2) The classic: mutable objects
Object identity versus equality is most likely to be an issue with mutable
objects. (Lua is to be congratulated for not having mutable strings IMHO.)
I find I rarely compare objects with == since I am more likely to have used
the object as a table key (and here I am assuming that tables will continue
to use object identity as a key comparator). This will be a little odd,
though: with equal tag methods, it is no longer the case that b == c
implies a[b] == a[c].
In general, one would want object identity in applications like serialising
(pickling in pythonspeak), but off the top of my jet-addled head, I can't
think of a piece of code which uses == rather than just stashing stuff in
3) This doesn't really fit here, but I'm curious. Under IEEE-754 numerical
equality, NaN is not equal to itself. However, it presumably is equal to
itself under object identity. How do I test to see if the result of a
computation is NaN? Do you contemplate an isNaN() function? Do I rely on
the slightly odd-looking IEEE-754 "if a ~= a then ..."?
Seems to me that the most readable is:
if a == NaN then ...
which would work (I hope) if == were object identity (and, presumably, ===
were IEEE-754 numerical equality).
Certainly if I were doing numerical computations, I would want to be able
to do the isNaN test rapidly.