lua-users home
lua-l archive

Re: Operator override and RE: Metatables for primitives performance?

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


Jerome Vuarand wrote:
Hi list,
I was porting an old C++/Java school project to Lua, and it contains a
vector3 class representing a position/vector in 3d space. Since I'm using
Lua 5.1 since the day it's out, I thought it would have been nice to use
the # operator to get the length of the vector. My vector is a table with
x, y and z fields, and I don't care about the length of the table itself.
My problem is that I then figured out that the # operator is not overridable for tables, since it already exists. I thought it was a bug of some kind, but
the Lua source seems to be explicit about that:
...
I have implemented a similar object. But I implemented it as a userdata with space for 3 floats. Then I override the __index and __newindex metamethods to access the components. The nice thing about this is that I can use a.y and a[1] styles of component access and get to the same components. I've also overridden arithmetic operations so I can add and subtract vectors. This method also allows the use of the '#' operator for length().
--
chris marrin ,"",ドル "As a general rule,don't solve puzzles
chris@marrin.com b` $ that open portals to Hell" ,,.
 ,.` ,b` ,` , 1$'
 ,|` mP ,` :$$' ,mm
 ,b" b" ,` ,mm m$$ ,m ,`P$$
 m$` ,b` .` ,mm ,'|$P ,|"1$` ,b$P ,` :1ドル
 b$` ,$: :,`` |$$ ,` $$` ,|` ,$,,ドル`"$$ .` :$|
b$| _m$`,:` :1ドル ,` ,$Pm|` ` :$,ドル..;"' |$:
P$b, _;b$$b1ドル" |$$ ,` ,$$" ``' $$
 ```"```'" `"` `""` ""` ,P`

AltStyle によって変換されたページ (->オリジナル) /