【问题标题】:C++ - Called Lua function always returns 0C++ - 被调用的 Lua 函数总是返回 0
【发布时间】:2015-06-26 02:15:29
【问题描述】:

我在玩 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;
}

为了尽可能简短,我删除了这段代码 sn-p 中的错误检查。

我使用这两个网站/教程作为参考:
https://csl.name/post/lua-and-cpp/
http://cc.byexamples.com/2008/07/15/calling-lua-function-from-c/

【问题讨论】:

  • 本机扩展函数返回错误代码,而不是实际返回值。因此,return result; 不会有任何好处。 (想想看,如果他们必须返回一个整数,他们将如何返回一个字符串、或nil、或一个表,甚至是一个浮点数(因为这是@ 987654327@ 预计)?
  • 啊,我明白了!非常感谢!

标签: c++ function lua return


【解决方案1】:

您应该将结果压入堆栈。 C 中的返回值告诉您实际返回了多少个值。

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

   lua_pushnumber(L, result);
   return 1;
}

【讨论】:

  • 好的,我明白了!非常感谢:)!
  • return 0 不是表示返回值的数量(在这种情况下为 1)吗?
  • @IllidanS4 我的错误,感谢您的更正。这次我检查了参考Programming in Lua
猜你喜欢
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 2017-10-20
  • 2016-07-21
  • 1970-01-01
  • 2013-09-02
  • 2011-08-27
  • 1970-01-01
相关资源
最近更新 更多