使用Luabind时,在比较存储的C++对象指针时,Lua函数会崩溃。

我刚刚开始学习Luabind和C++。我的目标很简单:

我想创建一个Lua函数,它以C++对象指针作为参数并将对象存储在Lua变量中。每次调用Lua函数时,它应该首先检查传递给它的对象指针是否与上一次调用期间存储的对象指针相同。

以下是全部代码:

当我运行此程序时,我希望看到以下输出:

但是,当我运行程序时,在比较'x'和'v'期间,在第二次调用Lua函数期间程序崩溃。这是程序的实际输出:

可以看出,在第一次函数调用期间,在“v”设置之前和之后,比较工作正常。但是,在第二个函数调用期间,第一个比较失败。

我一定错过了非常明显的事情,但我真的搞不清楚是什么。有谁能看到我做错了什么吗?任何建议都非常感谢!

非常感谢, 马丁

点赞
用户2066153
用户2066153

我找到了解决方法。某种原因,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 = 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;
}
2013-02-13 06:49:22