简体   繁体   English

无法在 C++ 中存储 lua 返回值

[英]Can't store lua return value in C++

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.我有这个 C++ 代码需要调用 Lua function。当我得到 function 返回值时,一切都很好(“甚至打印结果”)但是当涉及到存储变量时,该值将消失。

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);
const char* answer = lua_tostring(LS, -1);

lua_tostring returns a pointer to a string in Lua VM. lua_tostring 返回一个指向 Lua VM 中的字符串的指针。
Lua is a language with GC, so this string will disappear after you pop it from Lua API stack: Lua 是一种带有 GC 的语言,所以这个字符串在你从 Lua API 堆栈中弹出后就会消失:

lua_pop(LS, 1);

You end up with a dangling pointer.你最终得到了一个悬垂的指针。

How to fix:怎么修:
Copy string's content somewhere before popping Lua string from Lua API stack.在从 Lua API 堆栈弹出 Lua 字符串之前,将字符串的内容复制到某处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM