0

I'm trying to add functionality in my program where I pass a C++ struct into Lua function let it play with it and then set it back to C++ program.

Lua function:

function test( arg )
    arg.var1 = arg.var1 * 2
    arg.var2 = 1
end

C++ function:

struct MyStruct
{
    int var1;
    int var2;
};

MyStruct arg;

arg.var1 = 2;
arg.var2 = 2;

lua_getglobal( L, "test" );

lua_newtable( L );

lua_pushstring( L, "var1" );
lua_pushinteger( L, arg.var1 );
lua_settable( L, -3 );

lua_pushstring( L, "var2" );
lua_pushinteger( L, arg.var2 );
lua_settable( L, -3 );

lua_pcall( L, 1, 0, 0 );

// now i want somehow to grab back the modified table i pushed to c++ function as arg
arg.var1 = lua_*
arg.var2 = lua_*

so that I end up with this:

arg.var1 == 4
arg.var2 == 1

But I have no idea how I could do this, is it possible?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
kokodude
  • 13
  • 2

1 Answers1

1

I see two ways:

  1. Make test return arg. In this case, use lua_pcall( L, 1, 0, 1 ).

  2. Duplicate arg on the stack before calling test by adding these lines before lua_pcall:

--

lua_pushvalue( L, -1 );
lua_insert( L, -3 );

Either way, after test returns, you can get its fields with lua_getfield.

lua_getfield(L,-1,"var1")); arg.var1 = lua_tointeger(L,-1);
lua_getfield(L,-2,"var2")); arg.var2 = lua_tointeger(L,-1);
lhf
  • 70,581
  • 9
  • 108
  • 149
  • what i have to pass to getfield and getinteger to get the values with second solution? – kokodude Apr 08 '15 at 21:43
  • Alternatively, make it a lua global via lua_setglobal. I'm pretty sure there's an API for C code to have "hidden" globals, but I can't find it now. – Mooing Duck Apr 08 '15 at 22:02