[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: how to make anydimensional array?
- From: "Pavol Severa" <pavol.severa@...>
- Date: Sun, 23 Apr 2006 13:47:10 +0200
I'd like to ask what is the most "luaic" implementation of polynomials
in n variables
I was naturally thinking of a table t, with t.dim equal to n, and (say)
t[{k1,k2,..,kn}] equal to the coefficient of the polynomial in front
of (x1^k1 * x2^k2 * .. *xn^kn)
(the 'default value' of the table would not be nil, but rather 0, and
one would implement operations with polynomials using a metatable of
t).
The problem is of course that
t={}
t[ {1,2,3} ]=2
print( t[ {1,2,3} ] )
--> nil
so I tried to overcome {1,2,3}~={1,2,3} with an __eq field in a metatable:
--------------------------------
meta={}
function meta.__eq(x,y)
for i,e in ipairs(x) do
if e~=y[i] then return false
end
return true
end
function ind(...)
local result={...}
setmetatable(result,meta)
return result
end
---------------------------------
now ind(1,2,3)==ind(1,2,3)
but to my surprise
t={}
t[ind(1,2,3)]=2
print( t[ ind(1,2,3) ] )
--> nil
So what is a sane solution for this problem? I can imagine rewriting
the function ind so that it returns a string, e.g.
ind(1,2,3)=="1,2,3", and writing a reverse function
rev("1,2,3")==1,2,3. Would that be reasonable? Or should I play with
the metatable of t so that
t[ {1,2,3} ]=2
print( t[ {1,2,3} ] )
-->2
?
(by using the function ind in __index and __newindex? or by other means?)
Or any other solution?
(these are questions from a newbie, of course)
Best regards
P.