• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

How works metamethods? (1 Viewer)

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
75
Reaction score
46
Location
Italy
Website
github.com
First of all, you don't call it: Lua does. You write a metamethod precisely to tell Lua what to do when a certain operation is performed on a value of a certain type.

To see how to declare metamethods, I'll leave you below a simple example (it should work so I'll advise you to try running it and tinker with it, e.g. implementing other metamethods):

Lua:
-- Implementation of a type ('vec') representing a 2D vector.
-- An object of the 'vec' type is a table whose first and second elements are
-- numbers representing the x and y coordinates, respectively, and having the
-- table 'mt' defined below as its metatable.

local mt = {} -- the metatable for the 'vec' type

local function vec(x, y)
-- This is the constructor. It creates and returns a new object of the 'vec' type.
   local v = {x or 0, y or 0}
   setmetatable(v, mt)
   return v
end

-- Define a few metamethods for objects of the 'vec' type:

mt.__tostring = function(v) -- Lua calls this when it wants to coerce a vec to a string
   return "{"..v[1]..", "..v[2].."}"
end

mt.__concat = function(a, b) -- called when the object is an operand of .. 
   return tostring(a) .. tostring(b)
end

mt.__add = function(a, b) -- called when the object is an operand of + 
   local v = vec(a[1]+b[1], a[2]+b[2])
   return v
end

mt.__sub = function(a, b) -- called when the object is an operand of -
   local v = vec(a[1]-b[1], a[2]-b[2])
   return v
end

---------------------------------------------------------------------------
-- Example usage:
local v1 = vec(1, 2)
local v2 = vec(3, 4)

print(v1)
print(v2)
local v3 = v1 + v2
print(v3)
print("v2-v1 = ".. v2 - v1)
print("v1+v2 = ".. v1 + v2)
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
75
Reaction score
46
Location
Italy
Website
github.com
So I can just redefine the existing metamethods, right?

More or less so. It depends. Here I'd suggest you to re-read carefully the relevant manual section (manuals are like that: every time you read them you discover something that you didn't catch the last time...).

By the way, if you are looking to metamethods to find answers to this question, keep in mind that metatables are associated to values, not to variables. There are actually no variables in Lua: just names, values, and dynamic associations between them.
 
Top