使用Lua时在C ++中堆叠展开 [英] Stack unwinding in C++ when using Lua

查看:185
本文介绍了使用Lua时在C ++中堆叠展开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近偶然发现这个C ++ / Lua错误

I recently stumbled into this this C++/Lua error

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无法解开堆栈。

The error is that luaL_error use longjmp, so the stack is never unwound and s is never destructed, leaking memory. There are a few more Lua API's that fail to unwind the stack.

一个显而易见的解决方案是在C ++模式下编译Lua例外。然而,我不能像Luabind需要标准的C ABI。

One obvious solution is to compile Lua in C++ mode with exceptions. I, however, cannot as Luabind needs the standard C ABI.

我当前的想法是编写我自己的模拟Lua API的麻烦部分的函数:

My current thought is to write my own functions that mimic the troublesome parts of the 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 的堆栈正确解开。

So my question: Is function_for_lua's stack properly unwound. Can something go wrong?

推荐答案

如果我理解正确,使用 Luabind 抛出异常的函数被正确地捕获和翻译。 (请参阅参考。)

If I understand correctly, with Luabind functions that throw exceptions are properly caught and translated anyway. (See reference.)

所以每当你需要指出一个错误,只是抛出一个标准的异常:

So whenever you need to indicate an error, just throw a standard exception:

void function_for_lua( lua_State* L )
{
    std::string s("Trouble coming!");
    /* ... */

    // translated into lua error
    throw std::runtime_error("something went wrong");
}


免责声明:我从来没有使用过Lubind。

这篇关于使用Lua时在C ++中堆叠展开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆