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.25k stars 519 forks source link

Crash when iterating over lua table that contains integer field #1645

Open gamagan opened 1 week ago

gamagan commented 1 week ago

I'm getting a crash that i don't understand. I'm using it from MSVC 2022, in C++. Script engine is Luajit 2.1

Problem: From Lua side, I define a script that looks basically like this:

local this = {}

this.callback_1 = function() ... end
this.callback_2 = function() ... end

return this

On the C++ side, I iterate over the returned table and grab references to the functions in the table:

void Foo::ProcessTable(sol::table table) {
    for (const auto& itr : table) {
        auto nameOpt = itr.first.as<std::optional<std::string>>();
        // Since Lua tables are arrays *and* maps, some entries might not have string keys.
        if (not nameOpt) {
            continue;
        }

                // Ignore whatever is not a function. 
        auto fun = itr.second.as<std::optional<sol::function>>();
        if (not fun) {
            continue;
        }

        auto& name = *nameOpt;

        if (name == "callback_1") {
            this->callback_1 = *fun;
                } else if (name == "callback_2") {
            this->callback_2 = *fun;
                } else {
                    // We don't recognize this callback. Just ignore it.
                }
         }
}

This works well. However, if I add an integer field to the Lua table, from the Lua side, it crashes on the for (....) part, after the int field is processed (which is skipped via if (not fun)).

For example, this makes it crash:

local this = {}

this.callback_1 = function() ... end
this.value = 42
this.callback_2 = function() ... end

return this