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.12k stars 500 forks source link

luaL_unref Exception on program exit #1431

Closed vdweller84 closed 1 year ago

vdweller84 commented 1 year ago

Hello,

This is most likely a mistake on my part rather than a bug.

I am using an extern global variable sol::state lua . Then I call InitLua() , which resides in another .cpp file, where that variable is initialized, open_libraries() is called, and other lua-related stuff is set up. Then the program loops (using SDL) and each frame lua events run. There are lua tables and functions stored in containers (std::vector).

The program runs normally and all events run OK. But when the program quits (ie the loop breaks and main() returns), for instance when users click the Close icon on the window, I get an exception right here in reference.hpp :

void deref(lua_State* L_) const noexcept {
    luaL_unref(L_, LUA_REGISTRYINDEX, ref);
}

My question is, what am I doing wrong and what is a "good practice" to avoid it? I encountered a topic some time ago discussing something similar but for the life of me I can't find it again.

Thanks a lot in advance.

Rochet2 commented 1 year ago

Usually this kind of error occurs when you store objects in wrong order in classes or you store multiple things in global variables or manually destroy the state while still holding references somewhere.

You need to destroy any references to lua before you destroy the sol::state. This means any sol::function, sol::object, sol::table and so on that you might have stored. All of them must be destroyed before sol::state.

vdweller84 commented 1 year ago

Thank you. A simple cleanup was all that was needed.