Skip to main content

low_luajit/lua/type/
thread.rs

1use crate::{AmountReturned, LuaState, ffi};
2
3/*
4#[repr(i32)]
5#[derive(Debug)]
6pub enum ThreadStatus {
7	/// This thread is operational.
8	Ok = ffi::LUA_OK,
9
10	/// This thread is suspended.
11	Yielded = ffi::LUA_YIELD,
12
13	/// This thread encountered an error while running.
14	RuntimeError = ffi::LUA_ERRRUN,
15
16
17}*/
18
19/// Thread related functions.
20impl LuaState {
21	/// Returns `true` if the value at the given acceptable `index` is a thread, `false` otherwise.
22	#[inline]
23	#[must_use]
24	pub fn is_thread(&self, index: i32) -> bool {
25		// SAFETY: self.as_ptr() is always valid.
26		unsafe { ffi::lua_isthread(self.as_ptr(), index) != 0 }
27	}
28
29	/// Returns `true` if the thread represented by this `LuaState` is the main thread of its state, `false` otherwise.
30	#[inline]
31	#[must_use]
32	pub fn is_main_thread(&self) -> bool {
33		// SAFETY: No elements are popped except the one element that is pushed by this function.
34		unsafe { self.access_mut(|lua| {
35			let main = lua.push_thread();
36			lua.pop_unchecked(1);
37			main
38		}) }
39	}
40
41	/// Pushes the thread represented by this `LuaState` onto the stack.
42	///
43	/// Returns `true` if this thread is the main thread of its state, `false` otherwise.
44	#[inline]
45	pub fn push_thread(&mut self) -> bool {
46		// SAFETY: self.as_ptr() is always valid.
47		unsafe { ffi::lua_pushthread(self.as_ptr()) != 0 }
48	}
49
50	/// Finishes the currently called [`CFunction`] similarly to [`LuaState::return_any`], while also suspending the running coroutine.
51	/// Once the coroutine is resumed again, it will resume from the [`CFunction`]'s caller.
52	///
53	/// The returned values will be returned to whoever had resumed the coroutine rather than the caller.
54	///
55	/// The `LuaState` wrapper is consumed to prevent invalidating the `AmountReturned` (the Lua state itself is left intact).
56	///
57	/// Unlike [`LuaState::return_any`],
58	/// `amount` may be negative or higher than the amount of elements currently held in the stack without panics.
59	///
60	/// # Lua Errors
61	///
62	/// Errors if called from the main thread *(and thus not a coroutine)*.
63	///
64	/// [`CFunction`]: ./type.CFunction.html
65	#[inline]
66	pub fn yield_any(self, amount: i32) -> AmountReturned {
67		// SAFETY: self.as_ptr() is always valid and when yielding you are supposed to return -1.
68		unsafe { AmountReturned::unchecked(ffi::lua_yield(self.as_ptr(), amount)) }
69	}
70}