From 5a06778fbcd09633fa70f6f25177c800eff4f694 Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Sun, 16 Jan 2022 20:57:43 +0000 Subject: [PATCH] Always restore original Lua state after creating Future in async call. Fixes #121 --- src/lua.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/lua.rs b/src/lua.rs index 6da6ccb..9e95b25 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -2283,6 +2283,22 @@ impl Lua { } } + struct StateGuard(*mut Lua, *mut ffi::lua_State); + + impl StateGuard { + unsafe fn new(lua: *mut Lua, state: *mut ffi::lua_State) -> Self { + let orig_state = (*lua).state; + (*lua).state = state; + Self(lua, orig_state) + } + } + + impl Drop for StateGuard { + fn drop(&mut self) { + unsafe { (*self.0).state = self.1 } + } + } + unsafe extern "C" fn call_callback(state: *mut ffi::lua_State) -> c_int { let extra = match ffi::lua_type(state, ffi::lua_upvalueindex(1)) { ffi::LUA_TUSERDATA => { @@ -2304,7 +2320,7 @@ impl Lua { } let lua = &mut (*upvalue).lua; - lua.state = state; + let _guard = StateGuard::new(lua, state); let mut args = MultiValue::new_or_cached(lua); args.reserve(nargs as usize);