我刚刚开始使用Luabind和C++。我的目标很简单:
我想创建一个Lua函数,它以C++对象指针为参数,并将对象存储在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 = vn
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"one_answers"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"之前和之后的第一次函数调用期间,比较都起作用。但是,在调用第二个函数期间,第一次比较失败。
我一定错过了一些非常明显的东西,但我真的不知道是什么。有人能看到我做错了什么吗?非常感谢您的任何建议!
非常感谢,Martin
我找到了解决方案。似乎出于某种原因,Lua希望使用重载的C++等于运算符来对两个对象执行比较,而不是对指针本身执行比较。通过创建一个重载的相等运算符,简单地比较两个对象的地址并将其绑定到Lua,我可以使其工作。
我仍然不确定为什么Lua只会在第二个函数调用中以这种方式进行比较,而不是第一个,但至少我现在有了一个可行的解决方案。
完整的修改工作版本如下:
extern "C" {
#include "lua.h"
#include "lualib.h"
}
#include <luabind/luabind.hpp>
#include <luabind/operator.hpp>
class Obj {
};
bool operator==(const Obj& a, const Obj& b) {
return &a == &b;
}
int main(int argc, char **argv) {
lua_State* cLuaState = luaL_newstate();
luabind::open(cLuaState);
luaL_openlibs(cLuaState);
luabind::module(cLuaState) [
luabind::class_<Obj>("Obj")
.def(luabind::const_self == luabind::const_self)
];
luaL_dostring(cLuaState, "
function func(v)n
print ("Before: x is same as v?")n
print (x == v)n
x = vn
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;
}