Chris Chris - 3 years ago 83
C++ Question

Passing Lua function to C++

I am making a GUI in C++.

I want a Lua script to register a Lua function with C++, so that when a button click is handled by C++, C++ will call a registered Lua function.

I have used the following SO post as a guide: http://stackoverflow.com/questions/4928973/how-do-you-pass-a-lua-function-to-a-c-function-and-execute-the-lua-function-seve

For some reason, with my changes, it is not working.

This is my Lua code:

-- this is button.setClickEvent
function self.setClickEvent(eventFunction)
uiButtonSetClickEvent(self.id, eventFunction)
end





function buttonClick()
print("yay it worked!")
end

button.setClickEvent(buttonClick)


Here is the C++ code

static int lua_uiButtonSetClickEvent(lua_State *L)
{
int argumentsCount = lua_gettop(L);
int argumentsMin = 2;
if(argumentsCount < argumentsMin)
cout << "Error at uiButtonSetClickEvent, incorrect number of arguments" << endl;

double buttonId = lua_tonumber(L, 1);
int event = luaL_ref(L, LUA_REGISTRYINDEX);

long i = uiButtonGetIndex(buttonId);
if(i != -1)
{
cout << "!!! Storing lua function reference" << endl;
uiButtons[i].luaClickEvent = event;
uiButtonSetClickEvent(buttonId, lua_uiButtonCallClickEvent);
}

return 0;
}

static void uiButtonSetClickEvent(double buttonId, void (&event)(double))
{
long i = uiButtonGetIndex(buttonId);
if(i != -1)
uiButtons[i].clickEvent = event;
}

static void lua_uiButtonCallClickEvent(double buttonId)
{
long i = uiButtonGetIndex(buttonId);
if(i != -1)
{
lua_rawgeti( L, LUA_REGISTRYINDEX, uiButtons[i].luaClickEvent);

if ( 0 != lua_pcall( L, 0, 0, 0 ) ) {
printf("Failed to call the callback!\n %s\n", lua_tostring(L, -1));
return;
}

uiButtons[i].luaClickEvent = luaL_ref(L, LUA_REGISTRYINDEX);
}
}


Everything happens as expected, up until the point at which

The result is a segmentation fault in
lua_uiButtonCallClickEvent
at the following line:

lua_rawgeti( L, LUA_REGISTRYINDEX, uiButtons[i].luaClickEvent);


The only difference I notice between the guide on SO and my implementation is that not only pass the Lua function to C++, but also a
buttonId
.

I do not know if the parameter offset is causing the problem or not.

The integer that references the Lua function is 3.

I have tried researching the Lua reference manual but have not been successful.

I believe the fix I am looking for is trivial, and I hope that you can help.

Thank you for reading

Answer Source

lua_close(L) was called too early, which destroyed the lua stack.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download