lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Chris <chris@wulfenia.com> wrote:
> Is it possible to implement this operator as a LUA extension,
> so my Users can write a vaild LUA statement like:
>
> mat = matrix:new(NumCols, NumRows)
> mat(1, 1) = 12
> mat(1, 2) = 56
> mat(2, 1) = 98
> mat(2, 2) = 32
> mat:delete()

If you don't require the arrays to be sparse, you could just create tables for the first n-1
dimensions, and let assignment do the rest. Wouldn't something like what I scetched out below do
the trick?

-- assumes you have the usual "deep copy" clone routine defined...

Matrix = { clone = clone }

function Matrix:new(rows)
   return Matrix:clone():dim(rows)
end

function Matrix:dim(rows)
   for r=1, rows do
      if not self[r] then
         self[r] = {}
      end
   end
   return self
end

function Matrix:delete()
   self = nil
end

mat = Matrix:new(5)
mat[1][1] = 12
mat[1][2] = 56
mat[2][1] = 98
mat[2][2] = 32

mat:dim(10)        -- redimension
matB = mat:clone() -- copy
mat:delete()       -- free

x = matB[2][1]
print (x) -- 98
matB:delete()

I guess this is only practical if the dimensions are few or very small.

Cheers,
Eric


__________________________________________________
Do You Yahoo!?
Yahoo! Messenger - Talk while you surf!  It's FREE.
http://im.yahoo.com/