lua-users home
lua-l archive

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


The comparison operators are a special case, unfortunately.

On Tue, Apr 15, 2008 at 2:48 PM, Dirk Feytons <dirk.feytons@gmail.com> wrote:
> On Tue, Apr 15, 2008 at 2:21 PM, Ralph Hempel
>  <rhempel@hempeldesigngroup.com> wrote:
>
> > Dirk Feytons wrote:
>  >
>  > >
>  > > I recently discovered one disadvantage of such an approach: relational
>  > > operators are only possible on operands of the same type. In other
>  > > words, you can't compare such a userdata object with a regular number
>  > > since it is by definition false. This might or might not be a problem,
>  > > depending on your specific needs but it's certainly something to keep
>  > > in mind.
>  > >
>  >
>  >  These can be implemented in the metatable as well. The Lua VM
>  >  determines that one side or the other of the comparison is a
>  >  userdata and then calls the operator in the metatable for that
>  >  userdata.
>  >
>  >  It is up to the C implementation of the userdata to either
>  >  issue an error message or make an attempt to cast the other
>  >  side of the operator if necessary.
>  >
>  >  It's probably best in this application to have a completely
>  >  separate userdata that is incompatible with "regular" Lua numbers.
>  >
>  >  At least you'll get decent error messages if you do mix up
>  >  the operands :-)
>
>  Are you really sure because this contradicts everything I observed
>  (and worked around).
>  The VM throws an error if the types of the operands are not equal; see
>  for instance lessequal() in lvm.c. Even if both operands are userdata
>  they have to have the same metamethods before the VM even calls any
>  metamethod; see for instance call_orderTM() in lvm.c.
>
>  --
>  Dirk
>