Vector manipulation in native extension

Does the following code (in a native extension) update the vector in the table? Or should I write back the new value to the table? And, if so, how should I do it? Am I doing something in a really bad way?

lua_rawgeti(L, POSITIONS_INDEX, i);
dmVMath::Vector3* p = dmScript::ToVector3(L, -1);
lua_pop(L, 1);
p->setX(0.0);

Thank you for your help!

You get pointer to vector. So if you change it, you wil also see changes in lua. I use same code in some my native extensions

Do you have any problems?

1 Like

Thanks @d954mas !

This is indeed what I was thinking, but I needed a confirmation since I was having a side effect in a different part of the code. Below I explain what my problem was, maybe this is of some help for somebody else.

The native code is implementing the equivalent of

p = p + dt * v

But there is a subtle difference. Since, p and v are vector3, in Lua this line is creating a new vector3 while the c code just updates the value of p.
Somewhere else I have a buffer, let call it bp, of the position values, the p above. And there I was making a beginner mistake: instead of

bp[i] = vmath.vector3(p)

I simply had

bp[i] = p.

Indeed this Lua assignment by reference and not by value has always puzzled me… In C it is clear when you are copying a pointer or a value…

So, my Lua version

p = p + dt * v

was hiding my mistake in the buffer update by creating a new vector3.

2 Likes