2013-02-12 36 views
2

我刚刚开始使用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”设置后的第一个函数调用期间的作品。但是,第一个比较在第二个函数调用期间失败。

我一定会错过一些非常明显的东西,但我真的不知道它是什么。任何人都可以看到我做错了什么?任何意见非常感谢!

非常感谢你, 马丁

+0

你得到什么实际的错误?您需要从Luabind异常对象中提取Lua错误。 – 2013-02-12 22:30:35

回答

3

我找到了解决办法。看起来出于某种原因,Lua希望使用重载的C++ equals运算符来对两个对象执行比较,而不是执行指针本身的比较。通过创建一个重载的相等运算符来简单地比较两个对象的地址并将它绑定到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; 
}