我最近偶然发现了这个C++/Lua错误
int function_for_lua( lua_State* L )
{
std::string s("Trouble coming!");
/* ... */
return luaL_error(L,"something went wrong");
}
Run Code Online (Sandbox Code Playgroud)
错误是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());
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:function_for_lua堆栈是否正确解开.可能会出错吗?
using namespace std;
float test1(float i){
return i * i;
}
int test2(int i){
return i+9;
}
struct Wrapper{
typedef void (*wrapper_type)(int);
template<class R, class A>
void wrap(string name,R (*fn) (A) ){
wrapper_type f_ = &Wrapper::wrapper1<R,A,fn>;
// in the real program, f_ would be passed in an array to some c library
wrappers[name] = f_;
}
void run(int i){
map<string,wrapper_type>::iterator it, end = wrappers.end();
for(it=wrappers.begin();it!=end;it++){
wrapper_type wt = (*it).second;
(*wt)(i);
}
}
template<class R, class A, R (*fn) (A)>
static …Run Code Online (Sandbox Code Playgroud)