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?

2

1 Answer

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest