Relational metamethods
When a table with a metamethod is used with a comparison operator the __eq, __lt, and __le metamethods are called. Lua only calls the relational metamethods when both tables have the same metatable. Lua always returns false when any relational operator is used to compare two objects which do not have the same metatables.
- __eq is called for the equality operators ==, !=, <>, and ~=
- __lt is called for the less than operator < and >=
- __le is called for the less than or equal to operator <= and >
Note that a>=b is the same as not (a<b), a!=b is not (a==b), and a>b is not(a<=b). The Lua interpreter automatically translates the relational operators so that the developer needs only implement the three metamethods shown above.
mt={}
mt["__eq"] = function(a,b)
for k,v in pairs(a) do
if b[k] != v then return false end
end
for k,v in pairs(b) do
if a[k] != v then return false end
end
return true
end
t1={1,2,3}
t2={1,2,3}
setmetatable(t1,mt)
setmetatable(t2,mt)
if t1 != t2 then error("Tables are not equal!",0) end