Lua - Fallback Cases of Arithmetic and Comparison Metamethods



Fallback refers to a condition where a corresponding metamethod is not present in the metatable. In such a case, Lua generally fallbacks to the default behavior for the operation or throws error. In this chapter, we'll explore fallback behavior of arithmetic and comparison metamethods with examples.

Fallback for Arithmetic and Comparison metamethods

  • When we try to perform any of the arithmetic or comparsion between tables and any one of the table have corresponding metamethod (__add, __sub, __mul, __div, __mod, __pow, __unm, __eq, __lt, __le) defined, then Lua will call that method and result will be returned accordingly.

  • But if none of the table is having corresponding metamethod implementation in the associated metatables or metatables are not associated at all, then Lua will throw error.

Example - Error in case of Arithmetic Operation as Fallback

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 - Handling Arithmetic Operation

main.lua

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

local metaAdd = { __add = function(a, b) return "Tables added successfully!" end }
setmetatable(table1, metaAdd)
-- prints Tables added successfully!
print(table1 + table2)

Output

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

Tables added successfully!

Example - Error in case of Comparision Operation as Fallback

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 - Handling Comparison Operation

main.lua

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

local metaEq = { __eq = function(a, b) return false end }
setmetatable(table2, metaEq)
-- prints false as objets are different
print(table1 == table2)

Output

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

false
Advertisements