【问题标题】:Lua function crashes when comparing stored C++ object pointers using Luabind使用 Luabind 比较存储的 C++ 对象指针时,Lua 函数崩溃
【发布时间】:2013-01-28 07:05:00
【问题描述】:

我刚刚开始使用 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' 之前和之后的第一个函数调用期间,比较都有效。但是,在调用第二个函数期间,第一次比较失败。

我一定遗漏了一些非常明显的东西,但我真的不知道它是什么。谁能看到我做错了什么?非常感谢任何建议!

非常感谢, 马丁

【问题讨论】:

  • 您遇到了什么实际错误?您需要从 Luabind 异常对象中提取 Lua 错误。

标签: c++ lua luabind


【解决方案1】:

我找到了解决方案。似乎出于某种原因,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-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    相关资源
    最近更新 更多