Lua metatable

This article is tagged with: Lua metatable and lua

lua metatable

--[[
Metatables allow you to, among other things, redefine operators.
Let's demonstrate with a simple vector "class".
--]]
Vector = {}
Vector.mt = {} -- The metatable we will be using
function Vector.new(x, y)
local vec = {}
setmetatable(vec, Vector.mt) -- "Link" the vector with the metatable
vec.x = x
vec.y = y
return vec
function Vector.add(u, v) -- Return the resulting vector of u+v
local result = Vector.new(u.x, u.y)
result.x = result.x + v.x
result.y = result.y + v.y
return result

--[[
This is where metatables get interesting, as we redefine the + operator
for vectors.
--]]
Vector.mt.__add = Vector.add

--[[
There are multiple predefined operators you can replace, such as:
__add(u+v), __sub(u-v), __mul(u*v), __div(u/v), __mod(u%v),
__unm(-u), __concat(u..v), __eq(u==v), __lt(u<v), --]]<="" __le(u<="v)," __len(#u),="" etc...="" textarea="">
<div class="answer_source">Source: <a href="http://lua-users.org/wiki/MetamethodsTutorial" target="_blank">lua-users.org</a></div>
<br/>

This article is tagged with: Lua metatable and lua