我最近偶然发现了这个 C++/Lua 错误
int function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
return luaL_error(L,"something went wrong");
}
错误是luaL_error
使用了longjmp
,所以堆栈永远不会展开,s
永远不会被破坏,内存泄漏。还有一些无法展开堆栈的 Lua API。
一个明显的解决方案是在 C++ 模式下编译 Lua 并带有异常。然而,我不能,因为 Luabind 需要标准的 C ABI。
我目前的想法是编写自己的函数来模仿 Lua API 的麻烦部分:
// just a heads up this is valid c++. It's called a function try/catch.
int function_for_lua( lua_State* L )
try
{
/* code that may throw Lua_error */
}
catch( Lua_error& e )
{
luaL_error(L,e.what());
}
所以我的问题是:function_for_lua
的堆栈是否正确展开。会不会出什么问题?
最佳答案
如果我理解正确的话,使用 Luabind
抛出异常的函数无论如何都会被正确捕获和翻译。 (参见 reference。)
所以每当你需要指示错误时,只需抛出一个标准异常:
void function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
// translated into lua error
throw std::runtime_error("something went wrong");
}
<子> 免责声明:我从未使用过 Lubind。
关于c++ - 使用 Lua 时在 C++ 中展开堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005865/