lua-users home
lua-l archive

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


The problem is that your proposition 1 is not following lua table
semantics (that may be considered as a normal semantic since tables
are evrywhere in lua). With the table semantics, matrix.position
returns a reference to the value of the "position" field in the matrix
table, so your proposition 3 would be valid but proposition 1 don't
create a new vector.

To make both work you don't have to return a vector, you can return a
proxy object that acts like a vector but in fact is a reference to the
matrix. It would modify the matrix if you modify it.

2006/5/20, Ivaylo Beltchev <ivo@adelphia.net>:
Hi

I am trying to create a library for matrix and vector operations. matrix and vector are going to be full userdata.

Vectors are easy. I can define __index to return x, y, or z, and __newindex to set them. Then I can do this:
1) a=vector.x -- get the value of x from the vector
2) vector.x=0 -- modify the vector

The matrices prove to be trickier. I want to be able to do this, like in C:
1) a=matrix.position -- get the value of the position (creates a new vector)
2) a=matrix.position.x -- get the value of x from the position
3) matrix.position.x=0 -- directly set the value inside the matrix

The problem is that (3) is equivalent to this:
3a) a=matrix.position; a.x=0
It will create a copy of the position, and set its x to 0. The actual matrix will not be modified. It would work in C because in C matrix.position is not the value of the position, but a reference to it.

I can change matrix.position to return a reference vector object, and any changes to it could be forwarded to the matrix. But then (1) will not work as intended. (2) will still work either way.

Any suggestions?

Thanks
Ivo