C ++ - 调用Lua函数总是返回0

时间:2015-04-19 11:54:48

标签: c++ function lua return

我正在玩C ++和Lua。我想要实现的是C ++调用Lua函数,传递2个参数并检索1个结果。该函数调用C ++函数,该函数返回添加2个参数(整数)的结果。但结果总是得到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/

1 个答案:

答案 0 :(得分:2)

您应该将结果推送到堆栈。 C中的返回值表示实际返回的值。

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

   lua_pushnumber(L, result);
   return 1;
}