一个C++和lua调用的简单问题。。。高分求高手!!!

2025-05-21 11:45:58
推荐回答(2个)
回答1:

#include 
#include "lua.hpp"
const char* script =
"index = 1;\n"
"story1 = \n"
"{\n"
"  \"C\",\n"
"  \"C++\"\n"
"};\n"
"function getStory()\n"
"  index = index + 1;\n"
"  return story1[index-1];\n"
"end;";

int main() {
    lua_State* pL = luaL_newstate();
    luaL_dostring(pL, script);
    
    lua_getglobal(pL, "getStory");
    lua_call(pL, 0, 1);
    const char* str = lua_tostring(pL, lua_gettop(pL)) //注意这里
    puts(str);
    
    lua_getglobal(pL, "getStory");
    lua_call(pL, 0, 1);
    str = lua_tostring(pL, lua_gettop(pL)); //注意这里
    puts(str);
    
    lua_close(pL);
    return 0;
}


你真不是把函数返回值在栈内所处的Index搞错了吗(……

回答2:

清除堆栈可以使用 lua_settop() 函数 将指定 index 之后的元素清除。

所以

lua_settop(pl,0) 就将整个栈清空了。

void lua_settop (lua_State *L, int index);


Accepts any index, or 0, and sets the stack top to this index. If the new top is larger than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.

#include 
#include "lua.hpp"
const char* script =
"index = 1;\n"
"story1 = \n"
"{\n"
"  \"C\",\n"
"  \"C++\"\n"
"};\n"
"function getStory()\n"
"  index = index + 1;\n"
"  return story1[index-1];\n"
"end;";
 
int main() {
    lua_State* pL = luaL_newstate();
    luaL_dostring(pL, script);
     
lua_settop(pl,0);
lua_getglobal(pL, "getStory");
    lua_call(pL, 0, 1);
    const char* str = lua_tostring(pL,1);
//推荐使用 lua_gettop() , lua_tostring(pL, lua_gettop(pL));
    puts(str);
lua_settop(pl,0);
    lua_getglobal(pL, "getStory");
    lua_call(pL, 0, 1);
    str = lua_tostring(pL,1);
    puts(str);
lua_settop(pl,0);
     
    lua_close(pL);
    return 0;
}