ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.18k stars 515 forks source link

How to return a Lua table from a C++ function? #1554

Closed UltraEngine closed 10 months ago

UltraEngine commented 10 months ago

I am trying to create a C++ function that returns a standard Lua table. In this case, I am converting my own C++ table structure into a normal Lua table (not a userdata). The code produces a crash when anything is assigned to the table t, in this function.

What is the correct way to do this?

sol::table cpptable::tolua() const
{
    sol::table t;
    switch (this->t)
    {
    case table::type::object:
        for (auto pair : *_m)
        {
            if (pair.first.get_type() == tablekey::type::name)
            {
                switch (pair.second.get_type())
                {
                case table::type::boolean:
                    t[std::string(pair.first)] = pair.second.b;
                    break;
                case table::type::number_float:
                    t[std::string(pair.first)] = pair.second.f;
                    break;
                case table::type::number_integer:
                    t[std::string(pair.first)] = pair.second.i;
                    break;
                case table::type::string:
                    t[std::string(pair.first)] = pair.second.s;
                    break;
                case table::type::object:
                    t[std::string(pair.first)] = pair.second.tolua();
                    break;
                }
            }
            else
            {
                switch (pair.second.get_type())
                {
                case table::type::boolean:
                    t[int64_t(pair.first)] = pair.second.b;
                    break;
                case table::type::number_float:
                    t[int64_t(pair.first)] = pair.second.f;
                    break;
                case table::type::number_integer:
                    t[int64_t(pair.first)] = pair.second.i;
                    break;
                case table::type::string:
                    t[int64_t(pair.first)] = pair.second.s;
                    break;
                case table::type::object:
                    t[int64_t(pair.first)] = pair.second.tolua();
                    break;
                }
            }
        }
        break;
    }
    return t;
}
UltraEngine commented 10 months ago

This appears to work:

    sol::table table::tolua(sol::state* L) const
    {
        sol::table t = sol::make_object(L->lua_state(), sol::new_table());