无法在C++中存储lua返回值
我有这个 C++ 代码需要调用 Lua 函数。当我得到函数返回值时,一切都很好(“甚至打印结果”),但是当涉及到存储变量时,该值将消失。
LS = luaL_newstate();
luaL_openlibs(LS);
lua_register(LS, "lua_HostFunction", Link::lua_HostFunction);
if (luaL_dofile(LS, "./src/solutions/16t20.lua") != LUA_OK) {
cout << "Error: File not found or invalid" << endl;
}
string pholder = "prob"+to_string(pi);
lua_getglobal(LS, cv.stringToChar(pholder));
if (!lua_isfunction(LS, -1)) {
cout << pholder << endl;
}
int argNum = 1;
switch(pi) {
case 18: {
char *ptr = strtok(ca, ":");
lua_pushstring(LS, ptr);
ptr = strtok(NULL, ":");
lua_pushstring(LS, ptr);
argNum = 2;
break;
}
default: {
lua_pushstring(LS, ca);
argNum = 1;
break;
}
}
if (lua_pcall(LS, argNum, 1, 0) != LUA_OK) {
cout << "Couldn't call function | " + pholder << endl;
}
if (!lua_isstring(LS, -1)) {
cout << "Not a string";
}
const char* answer = lua_tostring(LS, -1);
// Will print output, but never store
cout << answer << endl;
answers += answer;
lua_pop(LS, 1);
I have this C++ code that needs to call a Lua function. When I get the function return values, all is well and good ("Even printing the result") but when it comes to storing the variable, the value will disappear.
LS = luaL_newstate();
luaL_openlibs(LS);
lua_register(LS, "lua_HostFunction", Link::lua_HostFunction);
if (luaL_dofile(LS, "./src/solutions/16t20.lua") != LUA_OK) {
cout << "Error: File not found or invalid" << endl;
}
string pholder = "prob"+to_string(pi);
lua_getglobal(LS, cv.stringToChar(pholder));
if (!lua_isfunction(LS, -1)) {
cout << pholder << endl;
}
int argNum = 1;
switch(pi) {
case 18: {
char *ptr = strtok(ca, ":");
lua_pushstring(LS, ptr);
ptr = strtok(NULL, ":");
lua_pushstring(LS, ptr);
argNum = 2;
break;
}
default: {
lua_pushstring(LS, ca);
argNum = 1;
break;
}
}
if (lua_pcall(LS, argNum, 1, 0) != LUA_OK) {
cout << "Couldn't call function | " + pholder << endl;
}
if (!lua_isstring(LS, -1)) {
cout << "Not a string";
}
const char* answer = lua_tostring(LS, -1);
// Will print output, but never store
cout << answer << endl;
answers += answer;
lua_pop(LS, 1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
lua_tostring 返回一个指向 Lua VM 中字符串的指针。
Lua 是一种带有 GC 的语言,因此当您从 Lua API 堆栈中弹出该字符串后,该字符串就会消失:
您最终会得到一个悬空指针。
如何修复:
在从 Lua API 堆栈中弹出 Lua 字符串之前,将字符串的内容复制到某处。
lua_tostring returns a pointer to a string in Lua VM.
Lua is a language with GC, so this string will disappear after you pop it from Lua API stack:
You end up with a dangling pointer.
How to fix:
Copy string's content somewhere before popping Lua string from Lua API stack.