【发布时间】:2014-10-06 15:27:03
【问题描述】:
是否可以从 C/C++ 中获取 lua 堆栈中的所有错误?这是我尝试过的
c++
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
if (luaL_loadfile(L, "LuaBridgeScript.lua"))
{
throw std::runtime_error("Unable to find lua file");
}
int error = lua_pcall(L, 0, 0, 0);
while (error && lua_gettop(L))
{
std::cout << "stack = " << lua_gettop(L) << "\n";
std::cout << "error = " << error << "\n";
std::cout << "message = " << lua_tostring(L, -1) << "\n";
lua_pop(L, 1);
error = lua_pcall(L, 0, 0, 0);
}
}
卢阿:
printMessage("hi")
printMessage2("hi2")
输出:
stack = 1
error = 2
message = LuaBridgeScript.lua:1: attempt to call global 'printMessage' <a nil value>
即使堆栈大小为 0 或负数,我也尝试过循环,但我不明白堆栈如何为负数,并且在几次尝试后程序崩溃。
【问题讨论】:
-
我不确定我是否遵循。
lua_pcall将在捕获第一个错误后立即返回。它将在printMessage处停止,并且不会继续执行该块。你从哪里得到堆栈上会有更多错误的想法? Docs 清楚地说明了这一点。 -
顺便说一句,你为什么在 main 中抛出错误?
-
我认为既然 lua_pcall 将函数从堆栈中弹出,它将在整个文件中继续执行,我想这不正确?你知道我该怎么做吗?至于抛出,我只是从一个函数中复制并粘贴它,并将其包装在 main 中。
-
你想达到什么目的?检查源文件是否有任何错误?
-
是的,我希望能够检查 lua 文件是否有错误,例如调用未定义的函数,或者忘记在函数后加上“结束”。