Lua - Overloading Operators



Lua table by default cannot handle arithmetic operations on them using arithmetic operators like +, - , * and so. But metatables provides certain specialized fields to overload arithmetic operators.

  • __add to overload addition (+) operator.

  • __sub to overload subtraction (-) operator.

  • __mul to overload multiplication (*) operator.

  • __div to overload division (/) operator.

There are __mod for modulus, __pow for power computation as well. These metamethods allows to define the behavior of the table used with arithmetic operators. This is especially useful, when we need to deal with custom data types like vectors, matrices or complex numbers.

Example - Error in using + Operator on tables

In case, we're not having __add metamethod for any of the table, Lua will complain with an error as shown in example below −

main.lua

-- table 1
local table1 = {}
-- table 2
local table2 = {}

-- below statement throws error - syntax error near '+'
table2 + table2  

Output

When we run the above program, we will get the following output−

lua: main.lua:7: syntax error near '+'

Example - Overloading + Operator

In below example, we've a more relevant example where two vectors are to be added. In order to add two vectors using + operator, we've implemented __add metamethod as shown below −

main.lua

-- create a metatable for Vector
local Vector = {
   -- overload + operator
   __add = function(v1, v2)
      return { x = v1.x + v2.x, y = v1.y + v2.y }
   end
}

-- method to create a vector instance
function Vector.new(x, y)
  return setmetatable({ x = x, y = y }, Vector)
end

-- create vector instances
local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)

-- add vectors
local v3 = v1 + v2

-- prints 4 6
print(v3.x, v3.y)

Output

When we run the above program, we will get the following output−

4
6
Advertisements