我刚刚开始使用Luabind和C++。我的目标很简单:Lua函数在使用Luabind比较存储的C++对象指针时崩溃
我想创建一个将C++对象指针作为参数并将该对象存储在Lua变量中的Lua函数。每次调用Lua函数时,都应该首先检查传递给它的对象指针是否与上次调用期间存储的对象指针是相同的对象指针。
下面是完整的代码:
extern "C" {
#include "lua.h"
#include "lualib.h"
}
#include <luabind/luabind.hpp>
class Obj {
};
int main(int argc, char **argv) {
lua_State* cLuaState = luaL_newstate();
luabind::open(cLuaState);
luaL_openlibs(cLuaState);
luabind::module(cLuaState) [
luabind::class_<Obj>("Obj")
];
luaL_dostring(cLuaState, "\
function func(v)\n\
print (\"Before: x is same as v?\")\n\
print (x == v)\n\
x = v\n\
print (\"After: x is same as v?\")\n\
print (x == v)\n\
end");
Obj* o = new Obj();
try {
luabind::call_function<void>(cLuaState, "func", o);
luabind::call_function<void>(cLuaState, "func", o);
} catch (std::exception &e) {
std::cout << "Exception thrown: " << e.what() << std::endl;
return 1;
}
return 0;
}
当我运行这个程序,我希望看到以下的输出:
Before: x is same as v?
false
Setting v
After: x is same as v?
true
Before: x is same as v?
true
Setting v
After: x is same as v?
true
然而,当我运行该程序,其过程中崩溃在'x'和'v'之间进行比较时第二次调用Lua函数。这是从程序输出结果的实际:
Before: x is same as v?
false
Setting v
After: x is same as v?
true
Before: x is same as v?
Exception thrown: lua runtime error
*** Exited with return code: 1 ***
可以看出,比较之前和“V”设置后的第一个函数调用期间的作品。但是,第一个比较在第二个函数调用期间失败。
我一定会错过一些非常明显的东西,但我真的不知道它是什么。任何人都可以看到我做错了什么?任何意见非常感谢!
非常感谢你, 马丁
你得到什么实际的错误?您需要从Luabind异常对象中提取Lua错误。 – 2013-02-12 22:30:35