[英]Stack unwinding in C++ when using Lua
我最近偶然发现了这个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
函数可以正确地捕获和翻译抛出异常。 (见参考文献 。)
因此,无论何时需要指出错误,只需抛出一个标准异常:
void function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
// translated into lua error
throw std::runtime_error("something went wrong");
}
免责声明:我从未使用过Lubind。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.