C Calling the Lua function is a problem to consider _lua

Source: Internet
Author: User
Tags event listener lua nref

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
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.