C ++ - 调用Lua函数始终返回0

我正在尝试使用 C++ 和 Lua。我想要实现的是 C++ 调用一个 Lua 函数,传递 2 个参数并检索 1 个结果。该函数调用一个返回两个参数(整数)相加结果的 C++ 函数。但我总是得到 0 作为结果。

Lua 脚本:

function f (x, y)
   return AddC(x, y)
end

C++ 代码:

#include "C:\Program Files (x86)\lua\5.3\include\lua.hpp"
#include <iostream>

class LuaState {
public:
   LuaState() : L(luaL_newstate()) {}
   ~LuaState() { lua_close(L); }

   inline operator lua_State*() { return L; }
private:
   lua_State* L;
};

int Addition(lua_State* L) {
   int amount = lua_gettop(L);
   std::cerr << "number of arguments: " << amount << std::endl;

   int first_number = lua_tointeger(L, 1);
   int second_number = lua_tointeger(L, 2);
   int result = first_number + second_number;

   std::cerr << "Addition: " << first_number << " + " << second_number << " = " << result << std::endl;

return result;
}

void InitializeLua(lua_State* L) {

   luaL_openlibs(L);
   luaopen_io(L);
   luaopen_base(L);
   luaopen_math(L);

   lua_register(L, "AddC", Addition);
}

int main(int argc, char* argv[])
{

   int first_number {0};
   int second_number {0};
   int result {0};
   LuaState L;

   InitializeLua(L);

   std::cout << "First number: ";
   std::cin >> first_number;

   std::cout << "Second number: ";
   std::cin >> second_number;

   int status = luaL_loadfile(L, "script.lua");
   luaL_dofile(L, "script.lua");
   lua_getglobal(L, "f");

   lua_pushnumber(L, first_number);
   lua_pushnumber(L, second_number);

   lua_pcall(L, 2, 1, 0);
   result = lua_tointeger(L, -1);

   std::cout << first_number << " + " << second_number << " = " << result << std::endl;
   lua_pop(L, 1);

   return 0;
}

为了保持代码尽可能简短,我在这段代码片段中省略了错误检查。

我使用了下面这两个站点/教程作为参考:

https://csl.name/post/lua-and-cpp/

http://cc.byexamples.com/2008/07/15/calling-lua-function-from-c/

点赞
用户88888888
用户88888888

你应该将结果推到栈中。在C中的返回值告诉你实际返回了多少个值。

int Addition(lua_State* L) {
   // ...

   lua_pushnumber(L, result);
   return 1;
}
2015-04-19 12:26:38