Primitive
Primitive

Reputation: 111

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.

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);

Upvotes: -1

Views: 270

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

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

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:

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.

Upvotes: 1

Related Questions