lua-users home
lua-l archive

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


A few potential solutions:

1. Make vectors and matrices immutable--that is, once created, their 
components can be read, but cannot be changed. This is really not as limiting 
as it first seems; I've used it from the beginning in my engine, with no 
unwanted results. As long as you have operators and functions that return new 
matrices, you can do the same things as before. To increase efficiency in 
places, I've compromised somewhat: matrices are mutable, but only from the 
C++ side, which is responsible for ensuring that matrices visible to Lua are 
not mutated. 

If you take this route, simply don't put a __newindex metamethod on, and Lua 
will dilligently shortstop any attempts at setting new values.

2. Have the position vector be returned as a reference to the actual vector 
within the matrix. Depending on how you expose userdata, and how you've 
programmed your classes, this will be easy or difficult. If it is difficult, 
consider a more thorough rewrite.

Hope this helps,

Ben

On Sunday 24 August 2003 11:02 pm, Ivaylo Beltchev wrote:
> Hi.
>
> I've been playing with Lua for the last week or so and I love it :)). I
> created classes for matrices and vectors as userdata from C++. A vector has
> x, y and z components (floats) and a matrix has right, front, up and
> position components as vectors. The memory layout inside the userdata
> matches exactly my C++ classes for matrix and vector. I override the
> __index and __newindex metamethods for the classes to get and set the
> components. Most of it works perfectly. However there is a small problem.
>
> Lets say m is a matrix and I want to change the x coordinate of the
> position:
>
> m=Matrix()
> m.pos.x=10
>
> This doesn't work because m.pos creates a new temp vector, whose x
> coordinate I change. In the C++ variant of the same code m.pos is a
> reference to the actual position inside the matrix and m.pos.x=10 works
> correctly. Is it possible to achieve the same result in Lua? If not, is it
> possible to make that code to generate an error?
>
> Thanks
> Ivo