Операторы равенства

Перегрузка операторов

local Point = {}
Point.__index = Point

function Point.new(x, y)
  return setmetatable({x = x, y = y}, Point)
end

function Point.__eq(a, b)
  return a.x == b.x and a.y == b.y
end

local p1 = Point.new(1, 1)
local p2 = Point.new(2, 2)
local p3 = Point.new(1, 1)

local equal1 = p1 == p2
-- equal1 = false
local equal2 = p1 == p3
-- equal2 = true

-- ~= negates __eq: no metamethod of its own
local equal3 = p1 ~= p3
-- equal3 = false

-- __eq is called only for two tables:
-- a table never equals a number
local equal4 = p1 == 1
-- equal4 = false

print("equal1 = " .. tostring(equal1))
print("equal2 = " .. tostring(equal2))
print("equal3 = " .. tostring(equal3))
print("equal4 = " .. tostring(equal4))