c++和lua相互调用过程
static void register_table_module(lua_State* L) //注册函数 lua调用c++的函数
{
lua_getglobal(L, "_G");
if (lua_istable(L, -1))
{
tolua_open(L);
tolua_usertype(L, "Table");
tolua_cclass(L, "Table", "Table", "", NULL);
tolua_beginmodule(L, "Table"); //对应lua中的table模块,lua里面table
tolua_function(L, "sendMsg", tolua_Table_sendMsg);
tolua_function(L, "sendRecord", tolua_Table_sendRecord);
tolua_function(L, "sendResult", tolua_Table_sendResult); //lua里面table模块执行sendResult,就会调起c++中 tolua_Table_sendResult 函数
tolua_endmodule(L);
}
lua_pop(L, 1);
}
_pLuaEngine = new LuaEngine();
lua_State* L = _pLuaEngine->getLuaStack()->getLuaState();
register_table_module(L);
_pLuaEngine->executeString("require 'src/main'");
lua_State* L = _pLuaEngine->getLuaStack()->getLuaState();
lua_getglobal(L, "__G__ProcessPackage__"); //lua对应的函数名称
lua_pushinteger(L, pP->getNumberID()); //第一个参数,int类型
lua_pushinteger(L, cmdid);//第二个参数,int类型
lua_pushlstring(L, buffer, len); //第三个参数,string类型
_pLuaEngine->getLuaStack()->executeFunction(3); //执行函数,传递3个参数
delete _pLuaEngine;
main.lua
function __G__ProcessPackage__(numid, cmdid, data)
GLogic:processPackage(numid, cmdid, data)
end
self._table:sendResult(player._numid, totalScore) //lua调用c++