我有这个需要调用 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 << "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);