Skip to content

Adding using keyword and implement IDisposable pattern for lua_State #12

Description

@tilkinsc

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_StateL=luaL_newstate()){if(L!=0){// Do Lua stuff}}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions