2013-03-09 78 views
2

我想打電話從Lua代碼一些C++函數,並傳遞的Lua表中的參數,這樣的事情:是否有任何用於C++的Lua表迭代器封裝?

call_cpp_function_from_lua({ x = 10, y = 20 }) 

call_cpp_function_from_lua我想獲得和使用迭代器的Lua表的C++表示,像這樣的東西:

std::map<boost::variant<LuaTypesList>, boost::variant<LuaTypesList>>::iterator it = getLuaTableBegin(); 

我可以使用C API來做到這一點,但它是乏味容易出現錯誤,請參閱Iterating through a Lua table from C++?

+1

你可以看到http://lua-users.org/wiki/IteratorsTutorial – user1929959 2013-03-09 11:25:17

+3

@用iterator user1929959不同的例子:他的意思*** C++迭代器***,不是Lua迭代器。 – 2013-03-09 11:26:48

+0

「*但它很乏味容易出錯*」您將不得不以這種或那種方式編寫該代碼。除非你要求圖書館。 C++迭代器爲你做的唯一事情就是將它包裝在一個特定的接口中;該接口的實現是困難的部分。 – 2013-03-09 11:32:21

回答

1

QtLua library爲Lua表實現C++迭代器。它有Value::iteratorValue::const_iterator類,允許迭代Lua表。下面是關於如何使用他們簡單的例子:

// code from examples/cpp/value/iterate.cc:32 

    QtLua::State state; 

    // New lua table value 
    state.exec_statements("table = { a = 1, b = 2, c = 3 }"); 

    QtLua::Value table = state["table"]; 

    // Iterate over lua table from C++ code 
    for (QtLua::Value::const_iterator i = table.begin(); i != table.end(); i++) 
     qDebug() << i.key().to_string_p() 
       << i.value().to_string_p();