|
本帖最后由 书径尘 于 2015-3-16 09:46 编辑
先贴下代码:
- std::string CallLuaFunction(lua_State* pLuaState, const char* szFunction)
- {
- std::string strFunctionName;
- const char* szParam = ParseFunctionName(szFunction, strFunctionName);
- // get lua function
- lua_getglobal(pLuaState, strFunctionName.c_str()); // 将lua脚本文件中的目标函数压入到堆栈
- int paramCount = 0;
- int returnCount = 1;
- // 将各参数依次入栈
- if (szParam[0] != 0)
- {
- const char* szCurParam = szParam;
- while (szCurParam[0] != 0)
- {
- std::string strCurParamValue;
- bool bNumber = false;
- szCurParam = ParseNextParam(szCurParam, strCurParamValue, &bNumber);
- if (bNumber)
- {
- double value = atof(strCurParamValue.c_str());
- lua_pushnumber(pLuaState, value);
- }
- else
- {
- lua_pushstring(pLuaState, strCurParamValue.c_str());
- }
- paramCount++;
- }
- }
- // 调用脚本函数
- if (lua_pcall(pLuaState, paramCount, returnCount, 0) != 0) // 执行刚才被压入堆栈中的函数,最后两个参数分别是参数的数量和返回值的数量, 函数执行后会删除原来被压入到堆栈中的数据,接着会把返回值压入到堆栈
- {
- ErrorBox("error running function `%s': %s", szFunction, lua_tostring(pLuaState, -1));
- return "";
- }
- std::string strReturn;
- // 获取返回值
- {
- int iReturn = -returnCount;
- if (lua_isnumber(pLuaState, iReturn))
- {
- double value = lua_tonumber(pLuaState, iReturn);
- char szStr[32];
- sprintf_s(szStr, sizeof(szStr), "%f", value);
- strReturn = szStr;
- }
- else if (lua_isstring(pLuaState, iReturn))
- {
- const char* szValue = lua_tostring(pLuaState, iReturn);
- strReturn = szValue;
- }
- }
- lua_pop(pLuaState, 1);
- return strReturn;
- }
复制代码
被调用的函数(空函数):
function Script_Main()
end
看到上面最后一行lua_pop()函数了吧,如果不加这条代码,就会导致堆栈溢出(必须用while()死循环不停的调用这个lua函数才会发生,否则,重现不了,这个问题害的我花了整整一天去重现这个bug)
发这贴子,我就是想问,是不是调用了lua_getglobal()后,必须调用 lua_pop()函数?否则会堆栈溢出?
否则是什么原因呢?
|
|