I have a problem with sol::function that doesn’t make any sense.
I have this struct that is supposed to hold a sol2 Lua callback function that gets called from C++:
struct CustomBehaviour {
CustomBehaviour() = default;
CustomBehaviour(const CustomBehaviour &oth) {
m_on_update = oth.m_on_update;
}
CustomBehaviour &operator=(const CustomBehaviour &oth) {
m_on_update = oth.m_on_update;
return *this;
}
void set_on_update(sol::function func) {
assert(func && "not a valid callback");
m_on_update = std::make_shared<sol::function>(std::move(func));
std::cout << "set_on_update called, m_on_update setn";
}
void call_on_update() const {
if(m_on_update) {
try {
std::cout << "m_on_update is valid, calling it...n";
m_on_update->call();
} catch (const sol::error& e) {
std::cerr << "Error in CustomBehaviour::on_update lua function: " << e.what() << "n;
}
} else {
std::cout << "m_on_update is not set.n";
}
}
private:
std::shared_ptr<sol::function> m_on_update;
};
I won’t share the C++ code that calls that function because it has been tested to work.
Whenever the call_on_update()
gets called in C++ it outputs that the function doesn’t exist but if I call that same call_on_update()
function to Lua, it magically exist again and works without problems.
Like this:
local behaviour = spawner_ent:add_component_CustomBehaviour()
behaviour:set_on_update(function()
print("custom behaviour updated")
end)
behaviour:call_on_update()
So basically the sol::function only exists in Lua but not in C++.
I have tried:
- calling the function in C++ every way I can come up with,
- storing the functions in many different ways like C++ lambdas, normal stack variables, smart pointers etc.
Aatos Tapper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.