【问题标题】:How do I create a Lua Table in C++, and pass it to a Lua function?如何在 C++ 中创建 Lua 表,并将其传递给 Lua 函数?
【发布时间】:2010-10-02 00:17:10
【问题描述】:

在 C++ 中,我有一个 map<string, string>,其中包含未知数量的条目。如何将它传递给 Lua 函数,以便 Lua 函数可以将数据用作表?

【问题讨论】:

    标签: c++ string map lua lua-table


    【解决方案1】:

    如果你想要一个真正的 lua 表:

    lua_newtable(L);
    int top = lua_gettop(L);
    
    for (std::map::iterator it = mymap.begin(); it != mymap.end(); ++it) {
        const char* key = it->first.c_str();
        const char* value = it->second.c_str();
        lua_pushlstring(L, key, it->first.size());
        lua_pushlstring(L, value, it->second.size());
        lua_settable(L, top);
    }
    

    为您的地图替换正确的类型..

    【讨论】:

      【解决方案2】:

      几个选项...

      1. 将地图复制到新的 Lua 表中,并传递 Lua 表。

      2. 创建一个proxy table,通过元表的__index__newindex 元方法指导读写操作

      当然,(1)的缺点是所有的复制。

      (2) 的缺点是pairs() 不能在代理表上工作

      针对广义pairs 的Lua 修复讨论是in the wikithis mailing list thread。泛化pairs 预计用于Lua 5.2

      【讨论】:

      • 向元表添加一个迭代器函数应该不会太难,就像对表的pairs()一样。
      • 我通常选择选项 2;除非表很小,并且对只读表有很多请求。
      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 2019-03-23
      • 2015-03-13
      • 2013-04-14
      • 2021-12-22
      相关资源
      最近更新 更多