【问题标题】:Simplest lua function that returns a vector of strings返回字符串向量的最简单的lua函数
【发布时间】:2011-04-12 06:24:27
【问题描述】:

我需要一个非常简单的 c++ 函数,它调用一个返回字符串数组的 lua 函数,并将它们存储为 c++ 向量。该函数可能如下所示:

std::vector<string> call_lua_func(string lua_source_code);

(其中 lua 源代码包含一个返回字符串数组的 lua 函数)。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: c++ lua lua-c++-connection


    【解决方案1】:

    这里有一些可能对您有用的来源。它可能需要更多的润色和测试。它期望 Lua 块返回字符串数组,但稍作修改就可以调用块中的命名函数。因此,它按原样使用 "return {'a'}" 作为参数,而不是 "function a() return {'a'} end" 作为参数。

    extern "C" {
    #include "../src/lua.h"
    #include "../src/lauxlib.h"
    }
    
    std::vector<string> call_lua_func(string lua_source_code)
    {
      std::vector<string> list_strings;
    
      // create a Lua state
      lua_State *L = luaL_newstate();
      lua_settop(L,0);
    
      // execute the string chunk
      luaL_dostring(L, lua_source_code.c_str());
    
      // if only one return value, and value is a table
      if(lua_gettop(L) == 1 && lua_istable(L, 1))
      {
        // for each entry in the table
        int len = lua_objlen(L, 1);
        for(int i=1;i <= len; i++)
        {
          // get the entry to stack
          lua_pushinteger(L, i);
          lua_gettable(L, 1);
    
          // get table entry as string
          const char *s = lua_tostring(L, -1);
          if(s)
          {
            // push the value to the vector
            list_strings.push_back(s);
          }
    
          // remove entry from stack
          lua_pop(L,1);
        }
      }
    
      // destroy the Lua state
      lua_close(L);
    
      return list_strings;
    }
    

    【讨论】:

    • 非常感谢!你的代码帮了我很多忙!但是我忘了一件事,也许你也可以帮我解决这个问题:我需要 lua 函数来接收来自 c++ 的字符串,所以我需要一个额外的步骤来推送字符串参数并从 lua 函数访问它。如果您能提供帮助,那就太棒了。再次感谢!!
    • 在调用luaL_dostring()之前使用lua_pushstring(L, argument.c_str());将字符串压入堆栈,然后将luaL_dostring()更改为if(0 == luaL_loadstring(L, lua_source_code.c_str())) lua_pcall(L, 1, 1, 0));
    【解决方案2】:

    首先,记住 Lua 数组不仅可以包含整数,还可以包含其他类型作为键。

    然后,您可以使用 luaL_loadstring 导入 Lua 源代码。

    此时,剩下的唯一要求就是“返回向量”。 现在,您可以使用lua_istable 来检查一个值是否是一个表(数组),并使用lua_gettable 提取多个字段(参见http://www.lua.org/pil/25.1.html)并手动将它们一一添加到向量中。

    如果您不知道如何处理堆栈,似乎有一些tutorials 可以帮助您。为了找到元素的数量,我找到了这个mailing list post,这可能会有所帮助。

    目前,我没有安装 Lua,因此无法测试此信息。但我还是希望它有所帮助。

    【讨论】:

      【解决方案3】:

      不是你的问题的真正答案:
      在使用普通的 lua c-api 编写 c++ lua 接口代码时,我遇到了很多麻烦。然后我测试了许多不同的 lua-wrapper,如果你想实现或多或少复杂的东西,我真的建议 luabind。可以在几秒钟内为 lua 提供类型,对智能指针的支持效果很好,并且(与其他项目相比)文档或多或少都不错。

      【讨论】:

        猜你喜欢
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        • 2017-10-25
        • 2021-06-10
        • 1970-01-01
        • 2021-03-12
        • 2015-06-21
        相关资源
        最近更新 更多