sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Crash when iterating over lua table that contains integer field

Open gamagan opened this issue 1 year ago • 0 comments

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

gamagan avatar Nov 12 '24 17:11 gamagan