lua-users home
lua-l archive

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

On 11-Jun-07, at 2:36 PM, Steve Heller wrote:

Thanks for the example. But what is the syntax for
setting the metatable for numbers? I tried this:

debug.setmetatable( number,
	 { __eq = function( a, b )
	 	 return a <= b and b <= a

print( 3 == 4 )

but __eq doesn't seem to be called.

No, it won't be. __eq is only called under some very specific

-- both objects must be of the same primitive type
-- that type must be either TTABLE or TUSERDATA
-- both objects must have the same __eq metamethod

If the objects have the same primitive type, which is
not one of the two shown above, == is always primitive
(that is, for numbers numeric equality and for everything
else object identity.)

If the types differ, the objects are not equal.

Ordering comparisons have a slightly different rule:
-- if the objects are of different primitive types, an error is thrown
-- TNUMBER and TSTRING comparisons are always primitive
-- otherwise, if both objects have the same metamethod (__lt or __le,
   as appropriate -- <= and >= try both, < and > only try __lt),
   it's called
-- otherwise, an error is thrown.

== and ~= never throw an error (unless the __eq metamethod is
called and throws an error, which is probably a bad idea.)