本篇实现c++调用lua出错时win32如何显示堆栈信息
test.lua 文件
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
function Test(historyWin, historyCharge, Css)
print("Test")
aS = 0/0
tab = {}
tab.helloword("")
As=1
Bs=2
Cs=historyWin * historyCharge * Css
return As, Bs, Cs
end
方法一:脚本内部实现信息
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main(int argc, const char * argv[]) {
int a=0,b=0,c=0;
string *fs = getFileContext("test.lua"); //获取脚本内容
lua_State * m_L;
m_L = luaL_newstate();
luaL_openlibs(m_L); //需要--否则不会显示打印信息、还会出现各种未知错误信息
::lua_pushcfunction(m_L, PrintLuaStack);
if(!luaL_dostring(m_L,(*fs).c_str()))
{
int rst = lua_getglobal(m_L, "__G__TRACKBACK__");//通过函数名,压入错误处理函数
int erroFunc = 0;
if (lua_type(m_L, -1) == LUA_TFUNCTION)
erroFunc = lua_gettop(m_L); //获取 __G__TRACKBACK__ 栈位置 --当前栈位置
rst = lua_getglobal(m_L, "getA");
if (lua_type(m_L, -1) == LUA_TFUNCTION)
{
lua_pushnumber(m_L, 1);
int erro = lua_pcall(m_L, 1, 1, erroFunc);
if(!erro) {
if(lua_isnumber(m_L, -1))
a = (int)luaL_checkinteger(m_L, -1);
b = (int)luaL_checkinteger(m_L, -2);
c = (int)luaL_checkinteger(m_L, -3);
lua_pop(m_L, 3);
}
}
}
if(m_L)
lua_close(m_L);
getchar();
return 1;
}
方法二:c++源代码实现
int PrintLuaStack(lua_State *L)
{
lua_State* pLuaState = L;
int stackTop=lua_gettop(pLuaState);//获取栈顶的索引值
int nIdx = 0;
int nType;
std::string strErro = "";
//错误信息
for(nIdx = stackTop;nIdx > 0;--nIdx)
{
nType = lua_type(pLuaState, nIdx);
strErro += lua_typename(pLuaState,nType);
strErro += lua_tostring(pLuaState,nIdx);
strErro += "\n";
}
//debug.traceback
lua_getglobal(pLuaState, "debug");
lua_getfield(pLuaState, -1, "traceback");
int iError = lua_pcall( pLuaState, //VMachine
0, //Argument Count
1, //Return Value Count
0 );
const char* sz = lua_tostring(pLuaState, -1);
strErro += sz;
printf(strErro.c_str());
return 0;
}
int main(int argc, const char * argv[]) {
int a=0,b=0,c=0;
string *fs = getFileContext("test.lua");
lua_State * m_L;
m_L = luaL_newstate();
luaL_openlibs(m_L); //需要--否则不会打印信息
::lua_pushcfunction(m_L, PrintLuaStack);
int erroFunc = lua_gettop(m_L);
if(!luaL_dostring(m_L,(*fs).c_str()))
{
int rst = lua_getglobal(m_L, "Test");
if (rst != LUA_TFUNCTION)
return 1;
lua_pushnumber(m_L, 1);
lua_pushnumber(m_L, 13);
lua_pushnumber(m_L, 13);
int erro = lua_pcall(m_L, 3, 3, erroFunc);
if(!erro) {
if(lua_isnumber(m_L, -1))
a = (int)luaL_checkinteger(m_L, -1);
b = (int)luaL_checkinteger(m_L, -2);
c = (int)luaL_checkinteger(m_L, -3);
lua_pop(m_L, 3);
}
}
if(m_L)
lua_close(m_L);
getchar();
return 1;
}