1
\$\begingroup\$

I have C++ function (which runs some physical simulation inside my game engine) which looks like this:

void doSomePhysics( int nIters, Vec3d pos, Vec3d vel ){ /*... don't care ...*/ }

I want call this function from a lua script likes this:

doSomePhysics( 100, {1.0,-2.0,3.0}, {-8.0,7.0,-6.0} ) 

I'm trying to figure out how to make lua interface to this function.

I would like to do several general helper functions for passing 2D,3D and 4D vectors and matrices since I will heavily use them.

Here is sketch what I'm currently trying to do (But I know it is not correct):

void lua_getVec3(lua_State *L, Vec3d& vec ){
    // universal helper function to get Vec3 function argument from Lua to C++ function
    luaL_checktype(L, 1, LUA_TTABLE);
    lua_settop(L, 1);
    int a_size = lua_rawlen(L, 1);
    lua_rawgeti(L, 1, 1); vec.x = lua_tonumber(L, -1);
    lua_rawgeti(L, 2, 2); vec.y = lua_tonumber(L, -2);
    lua_rawgeti(L, 3, 3); vec.z = lua_tonumber(L, -3);
    lua_pop(L, 3);
}

int l_doSomePhysics(lua_State* L){
    // lua interface for doSomePhysics
    Vec3d pos,vel;
    int n = lua_tointeger(L, 1);
    lua_getVec3(L, pos );
    lua_getVec3(L, vel );
    doSomePhysics(n,pos,vel);
    lua_pushnumber(state, 123);
    return 1;
} 

I read several short tutorials 1 2 3 but it seems horribly complicated, confusing and error-prone ... I'm completely lost in stack indexes (what is my current position in the stack?, what is correct relative index? etc.). I'm reluctant to believe the most famous game scripting language needs sooooo much boiler-plate code and so much pain for interfacing every little function.


EDIT: answer is here

\$\endgroup\$

closed as off-topic by DMGregory, Alexandre Vaillancourt, Engineer, Gnemlock, Tyyppi_77 Aug 4 '17 at 12:54

  • This question does not appear to be about game development within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    \$\begingroup\$ I'm voting to close this question as off-topic because it's a cross-post on StackOverflow. In future, please post your question on only one StackExchange site. \$\endgroup\$ – DMGregory Aug 3 '17 at 16:48