




I hope you answer my questions.
local vector2_mt = {
__add = function(a, b) -- Vector addition
if (type(a) ~= type(b)) then error("type mismatch: 'table' and 'table' required, got '" .. type(a) .. "' + '" .. type(b) .. "'") end
return vector2(a.x + b.x, a.y + b.y)
end,
__sub = function(a, b) -- Vector subtraction
if (type(a) ~= type(b)) then error("type mismatch: 'table' and 'table' required, got '" .. type(a) .. "' + '" .. type(b) .. "'") end
return vector2(a.x - b.x, a.y - b.y)
end,
__len = function(a) -- Vector length
return math.sqrt(a.x^2 + a.y^2)
end,
__tostring = function(a) -- Vector serialisation
return "{" .. a.x .. "," .. a.y .. "}"
end
}
function vector2(x, y)
local v = {x = x, y = y}
setmetatable(v, vector2_mt)
return v
end
local v1 = vector2(1, 1)
print(v1) -- {1, 1}
print(#v1) -- 1.4142135623731
local v2 = vector2(3, 3)
print(v2) -- {3, 3}
print(v1 + v2) -- {4, 4}
print(v2 - v1) -- {2, 2}
print(v1 + 1) -- error
module("ClassName", package.seeall)
ClassName = {}
ClassName.__index = ClassName
ClassName.__type = "ClassName"
function ClassName:new(arg1, arg2, ...)
local self = setmetatable( {}, ClassName )
return self
end
return ClassName