kokodude
kokodude

Reputation: 13

Lua pass table to function, modify it and get it back in C++

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?

Upvotes: 0

Views: 931

Answers (1)

lhf
lhf

Reputation: 72312

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);

Upvotes: 1

Related Questions