[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Translating from a VERY "loose" language
- From: Steve Heller <steveheller@...>
- Date: Mon, 11 Jun 2007 13:45:28 -0700 (PDT)
--- Rici Lake <lua@ricilake.net> wrote:
>
> 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
> > end
> > }
> > )
> >
> > print( 3 == 4 )
> >
> > but __eq doesn't seem to be called.
>
> No, it won't be. __eq is only called under some very
> specific
> circumstances:
>
> -- 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.)
Ok, it looks as though I'll have to handle this during
the translation process, by writing a function
"isEqual" and replacing == and ~= by calls to that
function. Then I can check the types and give an error
message.
By the way, do you know why == and ~= behave
differently from <=, etc. in this regard? It seems
inconsistent, and makes for more work when you have
type issues to deal with.