这几乎是this question的副本;但是,答案表明这并没有解决我的问题,而且我没有直接使用luaL_dostring()
宏(虽然我我使用它扩展到的同一对调用)。鉴于此计划:
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <lua.hpp>
static int _foo(lua_State* L)
{
lua_pushinteger(L, 1);
lua_pushinteger(L, 2);
lua_pushinteger(L, 3);
printf("In foo(): pushed %d elements...\n", lua_gettop(L));
return 3;
}
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, _foo);
lua_setglobal(L, "foo");
// This leaves three results on the stack...
lua_pushcfunction(L, _foo);
lua_pcall(L, 0, LUA_MULTRET, 0);
int nresults = lua_gettop(L);
printf("After foo(): %d results left on the stack...\n", nresults);
lua_settop(L, 0);
// ... and so does this.
luaL_loadstring(L, "foo()");
lua_pcall(L, 0, 3, 0);
nresults = lua_gettop(L);
printf("After foo(): %d results left on the stack...\n", nresults);
lua_settop(L, 0);
// But this does NOT. Why?
luaL_loadstring(L, "foo()");
lua_pcall(L, 0, LUA_MULTRET, 0);
nresults = lua_gettop(L);
printf("After foo(): %d results left on the stack...\n", nresults);
return 0;
}
为什么最后一次调用lua_pcall(L, 0, LUA_MULTRET, 0)
而不是会在堆栈上留下任何结果?运行上述程序的输出是:
In foo(): pushed 3 elements...
After foo(): 3 results left on the stack...
In foo(): pushed 3 elements...
After foo(): 3 results left on the stack...
In foo(): pushed 3 elements...
After foo(): 0 results left on the stack...
我正在使用Lua 5.1.5 ......
答案 0 :(得分:6)
在第一次调用中,您将C函数foo推入堆栈然后调用它。但是luaL_loadstring创建了一个块,所以在第二次和第三次调用中你推送一个块然后调用它,但是块没有返回任何东西,块只调用foo()。因此
lua_pcall(L, 0, 3, 0);
在Lua堆栈上创建3个nil,因为Lua确保您提出的3个值都存在,即使chunk没有返回任何值。还
lua_pcall(L, 0, LUA_MULTRET, 0);
什么都不返回,因为块没有返回任何内容。
如果你想从Lua执行foo,把foo全局变量放在堆栈上:
lua_getglobal(L, "foo");
lua_pcall(L, 0, LUA_MULTRET, 0);
或者,让chunk返回foo()返回的内容:
luaL_loadstring(L, "return foo()");
lua_pcall(L, 0, LUA_MULTRET, 0);