Metatables and metamethods

Metamethods allow us to change the behavior of a table by writing custom functions for operators—such as comparing objects, arithmetical operations, and more. For example, let's say we would like to overload the "add" functionality of our table object with a new function that adds certain fields we select. Normally, the addition operation isn't valid on tables but, with metatables, we can overwrite the __add metamethod to perform whatever we need.

Arithmetic metamethods

The metamethods supported by Lua tables are as follows:

Metamethod

Description

__add

Addition operator

__mul

Multiplication operator

__sub

Subtraction operator

__div

Division operator

__unm

Negation operator

__pow

Exponentiation operator

Get Mastering the Nmap Scripting Engine now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.