1

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

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

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

有任何想法吗?

谢谢!

4

3 回答 3

2

这是一些可能对您有用的来源。它可能需要更多的润色和测试。它期望 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;
}
于 2010-09-19T05:11:42.060 回答
1

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

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

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

如果您不知道如何处理堆栈,似乎有一些教程可以帮助您。为了找到元素的数量,我找到了这个邮件列表帖子,这可能会有所帮助。

现在,我没有安装 Lua,所以我无法测试这些信息。但无论如何我希望它有所帮助。

于 2010-09-14T16:43:12.717 回答
0

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

于 2010-09-14T17:29:14.053 回答