function calc(operator)
return function(matA, matB)
local result = {}
for row = 1, #matA do
result[row] = {}
for col = 1, #matA[row] do
if operator == "+" then result[row][col] = matA[row][col] + matB[row][col]
elseif operator == "-" then result[row][col] = matA[row][col] - matB[row][col]
elseif operator == "*" then result[row][col] = matA[row][col] * matB[row][col]
elseif operator == "/" then result[row][col] = matA[row][col] / matB[row][col]
end
end
end
return Mat(result)
end
end
function signInversion(mat)
local result = {}
for row = 1, #mat do
result[row] = {}
for col = 1, #mat[row] do
result[row][col] = -mat[row][col]
end
end
return Mat(result)
end
function matConcat(mat)
local string = ""
for row = 1, #mat do
string = string.." {"..table.concat(mat[row], ", ").."},\n"
end
return "{\n"..
string..
"}"
end
local matMetatable = { __add = calc("+") ,
__sub = calc("-") ,
__mul = calc("*") ,
__div = calc("/") ,
__unm = signInversion ,
__tostring = matConcat
}
function Mat(mat)
return setmetatable(mat, matMetatable)
end
a = Mat({{1,2,3,4},{5,6,7,8},{9,10,11,12}})
print(a)
print(-a)
print(a+a+a)
print(-a-a-a)
print(a*-a)
print(a*-a*-a)
print(a/-a/a*-a)