我最近偶然发现了这个 C++/Lua 错误
int function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
return luaL_error(L,"something went wrong");
}
错误在于luaL_error
use 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
无论如何,抛出异常的函数都会被正确捕获和翻译。 (看参考 http://www.rasterbar.com/products/luabind/docs.html#exceptions.)
因此,每当您需要指示错误时,只需抛出一个标准异常:
void function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
// translated into lua error
throw std::runtime_error("something went wrong");
}
Disclaimer: I've never used Lubind.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)