tilkinsc / Lua.NET

[C# .NET Core 8.0] [Cross-Platform] Lua.NET contains full bindings to Lua5.1.5, Lua5.2.4, Lua5.3.6, Lua.5.4.6 and LuaJIT
MIT License
41 stars 4 forks source link

Adding `using` keyword and implement IDisposable pattern for lua_State #12

Open tilkinsc opened 9 months ago

tilkinsc commented 9 months ago

Proposal

lua_State should follow the IDisposable pattern to use the using keyword.

Concerns

Undefined Behavior occurs when lua_close(L) closes a lua_State a second time and can result in application crashes.

Implementation

To mitigate the undefined behavior resulting from lua_close(L)ing a lua_State twice, we can set Handle to 0 in each Lua API's lua_close(L) after the call to native lua_close(L). Further, if lua_close(L) knows how to handle 0 we do not need to do anything further; otherwise we need to also check if the Handle is 0 before calling the native. This ensures that Handle == 0 to detect if the lua_State is closed or not when implementing the IDisposable pattern.

Benefits

Clean integration with C#'s using feature when quickly spinning up a lua_State to process something. Capturing the lua_State variable in a scope to avoid leaking lua_State's. Unfortunately, there's no way to exit from a using statement other than a goto so there is an additional scope; which isn't a problem depending on design.

using (lua_State L = luaL_newstate())
{
    if (L != 0)
    {
        // Do Lua stuff
    }
}