简体   繁体   中英

C++ - Called Lua function always returns 0

I am playing around with C++ and Lua. What I am trying to achieve is that C++ calls a Lua function, passing 2 arguments and retrieves 1 result. That function calls a C++ function that returns the result of the addition of the 2 arguments (integers). But I always get 0 as a result.

Lua script:

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

C++ code:

#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;
}

To keep it as short as possible, I removed the error checking in this code snippet.

I used these 2 sites/tutorials as a reference:
https://csl.name/post/lua-and-cpp/
http://cc.byexamples.com/2008/07/15/calling-lua-function-from-c/

You should push the result onto the stack. The return value in C tells how many values you are actually returning.

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

   lua_pushnumber(L, result);
   return 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM