Search code examples
c++lua

How can I write a file with containing a lua table using sol2


I've settled on using lua as my config management for my programs after seeing posts like this and loving the syntax, and sol2 recently got released so I'm using that.

So my question is, how can I grab all the variables in my lua state and spit them out in a file?

say,

sol::state lua;
lua["foo"]["bar"] = 2;
lua["foo"]["foobar"] = lua.create_table();

would, in turn, eventually spit out

foo = {
    bar = 2
    foobar = {}
}

Is this at all possible and if so, how?


Solution

  • I used this serializer to serialize my table and print it out, really quite easy!

    This is what I came up with

    std::string save_table(const std::string& table_name, sol::state& lua)
    {
        auto table = lua["serpent"];
        if (!table.valid()) {
            throw std::runtime_error("Serpent not loaded!");
        }
        if (!lua[table_name].valid()) {
            throw std::runtime_error(table_name + " doesn't exist!");
        }
        std::stringstream out;
        out << table_name << " = ";
        sol::function block = table["block"];
        std::string cont = block(lua[table_name]);
        out << cont;
        return std::move(out.str());
    }