C++ 传递字符串给 Lua 出错

我正在尝试在 C++ 中使用 Lua 状态,并且我需要从 C++ 传递一个字符串给它,但是当我尝试调用我在 Lua 中编写的函数时,我会遇到错误 attempted to call nil value。它可以被编译到 Lua 环境中,但是当我输入表达式时出现错误。

int main(int argc, char** argv){
  lua_State *L;
  L = luaL_newstate();

  string buff;
  const char* finalString;

  luaL_openlibs(L);
  luaL_dofile(L,argv[1]);

  getline(cin, buff);

  lua_getglobal(L, "InfixToPostfix");
  lua_pushstring (L, buff.c_str());

  lua_pcall(L, 1, 1, 0);

  finalString = lua_tostring(L, -1);

  printf("%s\n", finalString);

  lua_close(L);

}

来自 Lua 文件:

function InfixToPostfix(str)

  print("before for loop")

  for i in string.gmatch(str, "%S+") do

它在显示错误之前不会到达打印输出部分

点赞
用户1944004
用户1944004

以下代码对我来说完全有效:

#include <iostream>
#include <string>
#include <lua.hpp>

int main(int argc, char** argv)
{
  lua_State *L;
  L = luaL_newstate();
  luaL_openlibs(L);

  if (argc != 2)
  {
    std::cerr << "Usage: " << argv[0] << " script.lua\n";
    return 1;
  }

  if ( luaL_dofile(L,argv[1]) != 0 )
  {
    std::cerr << lua_tostring(L, -1) << '\n';
    return 1;
  }

  std::string buff;
  std::getline(std::cin, buff);

  lua_getglobal(L, "InfixToPostfix");
  lua_pushstring (L, buff.c_str());

  if ( lua_pcall(L, 1, 1, 0) != 0)
  {
    std::cerr << lua_tostring(L, -1) << '\n';
    return 1;
  }

  if ( !lua_isstring(L, -1) )
  {
    std::cerr << "Error: Return value cannot be converted to string!\n";
    return 1;
  }

  const char * finalString = lua_tostring(L, -1);

  std::cout << finalString << '\n';

  lua_close(L);
}
function InfixToPostfix(str)
   print("before for loop")
   for i in string.gmatch(str, "%S+") do
      print(i)
   end
   return "Something"
end

对于 C++ 部分,你也可以使用 Selene 库。这样可以大大减少所需的代码量,也不需要手动进行错误检查。

#include <iostream>
#include <string>
#include <selene.h>

int main(int argc, char** argv)
{
  sel::State L{true};

  if (argc != 2)
  {
    std::cerr << "Usage: " << argv[0] << " script.lua\n";
    return 1;
  }

  L.Load(argv[1]);

  std::string buff;
  std::getline(std::cin, buff);

  std::string finalString = L["InfixToPostfix"](buff);

  std::cout << finalString << '\n';
}
2017-04-23 08:06:14