ks1322
ks1322

Reputation: 35795

Is there any Lua table iterator wrapper for C++?

I want to call some C++ function from Lua code and pass Lua table in parameters, something like this:

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

In call_cpp_function_from_lua I would like to get and use iterator for C++ representation of Lua table, something like this:

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

I can use C API to do it but it is tedious an error prone, see Iterating through a Lua table from C++?.

Upvotes: 2

Views: 644

Answers (1)

ks1322
ks1322

Reputation: 35795

QtLua library implements C++ iterators for Lua tables. It has Value::iterator and Value::const_iterator classes, allowing iteration of Lua tables. Here is a short example on how to use them:

// 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();

Upvotes: 1

Related Questions