Comparing Values โ€‹โ€‹of Different Types

At some point in the untouchable program, a comparison is made between the two Lua values:

return a==b; 

I need to turn this == into >= , so I came to the following hack:

 a = { value=5 } b = { value=2 } mt = { __eq = function (op1, op2) return op1.value >= op2.value end } setmetatable(a, mt) setmetatable(b, mt) print(a == b) 

And this gives the expected result ( true ). Now the problem is that a and b are in different contexts, so I cannot do this:

 setmetatable(a, mt) setmetatable(b, mt) 

Instead, I can do:

 mtA = { __eq = function (op1, op2) return op1.value >= op2.value end } setmetatable(a, mtA) mtB = { __eq = function (op1, op2) return op1.value >= op2.value end } setmetatable(b, mtB) 

But then a and b are of different types, and the == operator returns false , without even reaching the __eq overload.

Any idea on how to achieve what I need?

+4
source share
1 answer

Overriding __eq works fine with objects of different types under Lua 5.2; however, it should work fine in 5.1 if two metatets simultaneously point to the same function:

 local a, b = { value=5 }, { value=2 } local function meta_eq(op1, op2) return op1.value >= op2.value end setmetatable(a, { __eq = meta_eq }) setmetatable(b, { __eq = meta_eq }) print(a == b) -- true 

It can also be noted that in addition to __eq there are __gt and __ge that override> and> = respectively.

+3
source

Source: https://habr.com/ru/post/1440791/