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

我有这个需要调用Lua函数的C ++代码。当我获取函数返回值时,一切都很好(“即使打印结果”),但当涉及存储变量时,该值将消失。

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 <<“错误:未找到文件或无效”<< 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;
    }
    默认:{
        lua_pushstring(LS,ca);
        argNum = 1;
        break;
    }
}
if(lua_pcall(LS,argNum,10)!= LUA_OK){
    cout <<“无法调用函数|”+ pholder << endl;
}
if(!lua_isstring(LS,-1)){
    cout <<“不是字符串”;
}
const char * answer = lua_tostring(LS,-1);
//将打印输出,但从不存储
cout <<答案<< endl;
answers + = answer;
lua_pop(LS,1);

原文链接 https://stackoverflow.com/questions/71281092

点赞
stackoverflow用户1847592
stackoverflow用户1847592

``` const char* answer = lua_tostring(LS, -1);

lua_tostring返回Lua虚拟机中字符串的指针。

Lua是一种带有GC的语言,因此当您从Lua API堆栈中弹出它时,该字符串将消失:

lua_pop(LS, 1);

这将导致指针悬空。

如何修复:

在从Lua API堆栈中弹出Lua字符串之前将字符串内容复制到其他地方。

2022-02-27 00:22:13