Home

metamethod

Metamethod is a term used in Lua to describe a special kind of function stored in a metatable that defines or overrides the behavior of operations and other language constructs on values that carry that metatable. Metamethods are not methods of the value itself; they are functions that the Lua runtime can invoke automatically to implement operator overloading and related behavior.

How metamethods work: When Lua evaluates an operation such as addition, indexing, or a function call, it

Common metamethods include __add, __sub, __mul, __div, __mod, __pow, and __unm for arithmetic; __eq, __lt, and __le

Implementation and usage: A metatable is a regular table attached to a value via setmetatable, and metamethod

checks
the
involved
values
for
an
appropriate
metamethod.
If
a
suitable
metamethod
is
present
in
a
metatable—for
example,
__add
for
addition
or
__index
for
table
access—it
is
called
with
the
operands
to
produce
a
result.
If
no
metamethod
applies,
Lua
uses
the
default
behavior
or
raises
an
error.
Metamethods
can
also
customize
string
conversion
with
__tostring
or
function
invocation
with
__call.
for
comparisons;
__index
for
retrieving
fields;
__newindex
for
assigning
fields;
__call
to
make
a
value
callable;
__tostring
for
string
representation;
and
__concat
for
string
concatenation.
Some
versions
also
introduce
additional
metamethods
to
control
iteration
and
other
specialized
behavior.
keys
are
the
corresponding
function
values.
Metamethods
enable
patterns
such
as
object-like
behavior,
operator
overloading,
or
proxy
objects
while
preserving
the
underlying
type.
They
require
careful
design
to
avoid
unintended
recursion
and
performance
costs,
and
their
availability
and
specifics
can
vary
between
languages
that
implement
similar
concepts.