我刚刚开始使用 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 = 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”之前和之后的第一个函数调用期间,比较都有效。但是,在调用第二个函数期间,第一次比较失败。
我一定错过了一些非常明显的东西,但我真的不知道它是什么。谁能看到我做错了什么?非常感谢任何建议!
非常感谢你,马丁