The issues to consider:
1. Use Lua_pcall to call the LUA function, first put the LUA function into the stack, and then put the parameters into the stack, Lua_pcall (luastate, number of parameters, number of return values, 0);
2. To recall the LUA function when the event is triggered, you need to save the LUA function and use Lual_ref (Luastate, Lua_registryindex) to save the LUA function at the top of the stack to the Lua_registryindex table, Lua_r Egistryindex is a global table, LUAL_REF returns the position of the LUA function in the Lua_registryindex table nref;
3. Use Lua_rawgeti (luastate, Lua_registryindex, nref) to obtain the previously saved LUA function, Nref is the location of the LUA function in the Lua_registryindex table, and the LUA function will be placed on top of the stack, which You can use Lua_pcall to invoke the LUA function;
4. Use Lual_unref (luastate, Lua_registryindex, nref) to remove the previously saved LUA function from the Lua_registryindex table;
Example:
Copy Code code as follows:
int Luatest::attach (lua_state* luastate)
{
if (Lua_isfunction (luastate, 1)!= 1)
{
return 0;
}
Lua_settop (luastate, 1);
M_nref = Lual_ref (luastate, Lua_registryindex); Save to Lua_registryindex table
Lua_pushinteger (Luastate, nref);
return 1;
}
int luatest::D etach (lua_state* luastate)
{
M_nref = Lual_checknumber (luastate, 1);
Lual_unref (Luastate, Lua_registryindex, nref); removing from the Lua_registryindex table
M_nref = 0;
return 0;
}
Event Listener function
void Luatest::eventlistener (lua_state* luastate)
{
Lua_rawgeti (Luastate, Lua_registryindex, m_nref); Get from the Lua_registryindex table
Lua_pushstring (luastate, "parameter 1");
Lua_pushstring (luastate, "Parameter 2");
Lua_pcall (Luastate, 2, 1, 0); Calling the LUA function
int nret = Lual_checknumber (luastate,-1); return value
}