From 7961ba4565d6e7ee501f0b940089cc9c57dd1c61 Mon Sep 17 00:00:00 2001 From: Dennis Schridde Date: Wed, 27 Nov 2013 01:36:07 +0100 Subject: [PATCH] Extension for large (>3D) vectors and segment and x/y/z/w convenience Support for: local m = matrix{1,2,3,4,5,6,...} m:segment(3)[2] -->> matrix{2,3,4} m:y() -->> 2 --- lua/matrix.lua | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/lua/matrix.lua b/lua/matrix.lua index 83f7d57..e81951d 100644 --- a/lua/matrix.lua +++ b/lua/matrix.lua @@ -134,7 +134,11 @@ function matrix:new( rows, columns, value ) if type( rows ) == "table" then -- check for vector if type(rows[1]) ~= "table" then -- expect a vector - return setmetatable( {{rows[1]},{rows[2]},{rows[3]}},matrix_meta ) + local o = {} + for i,v in ipairs(rows) do + o[i] = {v} + end + return setmetatable( o,matrix_meta ) end return setmetatable( rows,matrix_meta ) end @@ -189,6 +193,43 @@ setmetatable( matrix, { __call = function( ... ) return matrix.new( ... ) end } -- but one should avoid using symbolic matrices with complex ones -- since it is not clear which metatable then is used + +local segment = {} + +function segment:__index(base_row) + local o = matrix(self.size,1) + for i=1,self.size do + o[i][1] = self.matrix[base_row+i-1][1] + end + return o +end + +function segment:__newindex(base_row, o) + assert(self.size == #o) + for i=1,self.size do + self.matrix[base_row+i-1] = o[i] + end +end + +function matrix:segment(size) + local o = {matrix=self, size=size} + return setmetatable(o, segment) +end + +function matrix:x() + return self[1][1] +end +function matrix:y() + return self[2][1] +end +function matrix:z() + return self[3][1] +end +function matrix:w() + return self[4][1] +end + + --// matrix.add ( m1, m2 ) -- Add two matrices; m2 may be of bigger size than m1 function matrix.add( m1, m2 )