Skip to content

Commit 44369f4

Browse files
committed
Implement LuaThread::close()
1 parent cd4091f commit 44369f4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/thread.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,41 @@ impl Thread {
373373
pub fn to_pointer(&self) -> *const c_void {
374374
self.0.to_pointer()
375375
}
376+
/// Closes a thread and marks it as finished.
377+
///
378+
/// In [Lua 5.4]: cleans its call stack and closes all pending to-be-closed variables.
379+
/// Returns a error in case of either the original error that stopped the thread or errors
380+
/// in closing methods.
381+
///
382+
/// In Luau: resets to the initial state of a newly created Lua thread.
383+
/// Lua threads in arbitrary states (like yielded or errored) can be reset properly.
384+
///
385+
/// Requires `feature = "lua54"` OR `feature = "luau"`.
386+
///
387+
/// [Lua 5.4]: https://www.lua.org/manual/5.4/manual.html#lua_closethread
388+
#[cfg(any(feature = "lua54", feature = "luau"))]
389+
#[cfg_attr(docsrs, doc(cfg(any(feature = "lua54", feature = "luau"))))]
390+
pub fn close(&self) -> Result<()> {
391+
let lua = self.0.lua.lock();
392+
if self.status_inner(&lua) == ThreadStatus::Running {
393+
return Err(Error::runtime("cannot reset a running thread"));
394+
}
395+
396+
let thread_state = self.state();
397+
unsafe {
398+
#[cfg(all(feature = "lua54", not(feature = "vendored")))]
399+
let status = ffi::lua_resetthread(thread_state);
400+
#[cfg(all(feature = "lua54", feature = "vendored"))]
401+
let status = ffi::lua_closethread(thread_state, lua.state());
402+
#[cfg(feature = "lua54")]
403+
if status != ffi::LUA_OK {
404+
return Err(pop_error(thread_state, status));
405+
}
406+
#[cfg(feature = "luau")]
407+
ffi::lua_resetthread(thread_state);
408+
Ok(())
409+
}
410+
}
376411
}
377412

378413
impl fmt::Debug for Thread {

0 commit comments

Comments
 (0)