gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:50:38 25 4
gpt4 key购买 nike

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

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

非常感谢,马丁

最佳答案

我找到了解决方案。似乎出于某种原因,Lua 想要使用重载的 C++ 等于运算符来对两个对象执行比较,而不是执行指针本身的比较。通过创建一个重载的相等运算符来简单地比较两个对象的地址并将其绑定(bind)到 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;
}

关于c++ - 使用 Luabind 比较存储的 C++ 对象指针时,Lua 函数崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com