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?

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

what i have to pass to getfield and getinteger to get the values with second solution?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.