lua-users home
lua-l archive

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


2015-06-16 17:42 GMT+02:00 Andrew Cagney <andrew.cagney@gmail.com>:

> I'd like to change the behaviour of __eq when applied to strings.  I
> suspect I'll need to somehow change the underlying string type?

> I suspect it is related to this:
>
> 2.4 – Metatables and Metamethods
> [...] "eq": the == (equal) operation. Behavior similar to the "add"
> operation, except that Lua will try a metamethod only when the values
> being compared are either both tables or both full userdata and they
> are not primitively equal. The result of the call is always converted
> to a boolean.
>
> Anyway, does anyone have a pointer or example showing how to do
> override __eq (and string operations more generally).

> The objective here is to fully integrate my objects into Lua.  That
> is, expressions such as:
>   o = "string"
>   i = i+1
>   if i == 1 or o == "string" then

The first line creates a value of type string and stores it in _ENV.o
unless you have overridden __newindex in _ENV, a risky thing to do.
And as the docs state, __eq will not be invoked in the third line.

What you can do is to redefine stuff not normally used for strings.
E.g. you can redefine string_mt.__not to be a constructor for your
wrapper type and string_mt.__xor and to be your intended __eq.
Then the following will work:

   o = ~"string"
   i = i+1
   if i == 1 or o ~ "string" then