请问C++是否可以动态查询Lua函数的返回值个数。
例如,我可以像这样在 C++ 中向/从 Lua 函数传递值和返回值。
/* push functions and arguments */
lua_getglobal(L, "f"); /* function to be called */
lua_pushnumber(L, x); /* push 1st argument */
lua_pushnumber(L, y); /* push 2nd argument */
/* do the call (2 arguments, 1 result) */
if (lua_pcall(L, 2, 1, 0) != 0)
error(L, "error running function `f': %s", lua_tostring(L, -1));
/* do something with the result */
如您所见,它期望从 Lua 函数返回 1 个值。因此,如果用户在 Lua 函数中返回多于(或少于)1 个值,它将无法正常工作。
是否有任何可能的解决方案来提前检测从 Lua 函数返回的值的数量,以便我可以在 C++ 中动态处理返回值?
最佳答案
这是对现有答案的扩展,概述了可能的实现方式。一旦将实现示例添加到现有示例,我将删除此答案。
#include <iostream>
#include <lua.hpp>
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <script.lua>\n";
return 1;
}
lua_State * L = luaL_newstate();
luaL_openlibs(L);
if (luaL_dofile(L, argv[1]) != 0) {
std::cerr << "lua: " << lua_tostring(L, -1) << '\n';
lua_close(L);
return 1;
}
int stack_size = lua_gettop(L);
lua_getglobal(L, "f");
lua_pushnumber(L, 1);
lua_pushnumber(L, 2);
if (lua_pcall(L, 2, LUA_MULTRET, 0) != 0) {
std::cerr << "lua: " << lua_tostring(L, -1) << '\n';
lua_close(L);
return 1;
}
int num_returns = lua_gettop(L) - stack_size;
std::cout << num_returns << " values returned\n";
lua_close(L);
}
function f(x,y)
return 1,2,3,"Hello World",{},function() end
end
6 values returned
关于c++ - 动态找出Lua function()的返回值个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920640/