C ++将字符串传递给lua错误

Posted

技术标签:

【中文标题】C ++将字符串传递给lua错误【英文标题】:C++ passing string to lua error 【发布时间】:2017-04-23 01:34:46 【问题描述】:

我正在尝试在 C++ 中使用 lua 状态,我需要从 C++ 传递一个 str,但是当我尝试调用我在 lua 中编写的函数时,我得到了错误 试图调用 nil 值。它直接编译到 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

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

【问题讨论】:

我相信错误消息“尝试调用 nil 值”表示全局名称不存在,正如您拼写的那样。原因可能是名称拼写错误或函数声明位于全局以外的某个范围内。请参阅***.com/questions/5559741/…,另请参阅***.com/questions/20380232/… 和cc.byexamples.com/2008/06/21/… 另一个可能的原因是 Lua 文件包含语法错误。你应该检查luaL_dofile的返回值。 【参考方案1】:

以下对我来说很好:

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

  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';

【讨论】:

以上是关于C ++将字符串传递给lua错误的主要内容,如果未能解决你的问题,请参考以下文章

使用 DLL 将 C# StringBuilder / 字符串传递给 C++ char*

通过引用将字符串数组传递给 C 函数

C ++将文件行传递给字符串向量

我收到此错误“传递给Illuminate Database Grammar :: parameterize()的参数1必须是类型

C ++将字符串传递给映射

将字节数组从 C 传递到 Lua