pub struct Thread(/* private fields */);Expand description
Handle to an internal Lua thread (coroutine).
Implementations§
Source§impl Thread
impl Thread
Sourcepub fn resume<R>(&self, args: impl IntoLuaMulti) -> Result<R>where
R: FromLuaMulti,
pub fn resume<R>(&self, args: impl IntoLuaMulti) -> Result<R>where
R: FromLuaMulti,
Resumes execution of this thread.
Equivalent to coroutine.resume.
Passes args as arguments to the thread. If the coroutine has called coroutine.yield,
it will return these arguments. Otherwise, the coroutine wasn’t yet started, so the
arguments are passed to its main function.
If the thread is no longer resumable (meaning it has finished execution or encountered an
error), this will return Error::CoroutineUnresumable, otherwise will return Ok as
follows:
If the thread calls coroutine.yield, returns the values passed to yield. If the thread
returns values from its main function, returns those.
§Examples
let thread: Thread = lua.load(r#"
coroutine.create(function(arg)
assert(arg == 42)
local yieldarg = coroutine.yield(123)
assert(yieldarg == 43)
return 987
end)
"#).eval()?;
assert_eq!(thread.resume::<u32>(42)?, 123);
assert_eq!(thread.resume::<u32>(43)?, 987);
// The coroutine has now returned, so `resume` will fail
match thread.resume::<u32>(()) {
Err(Error::CoroutineUnresumable) => {},
unexpected => panic!("unexpected result {:?}", unexpected),
}Sourcepub fn status(&self) -> ThreadStatus
pub fn status(&self) -> ThreadStatus
Gets the status of the thread.
Sourcepub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
Available on non-crate feature luau only.
pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
luau only.Sets a hook function that will periodically be called as Lua code executes.
This function is similar or Lua::set_hook except that it sets for the thread.
You can have multiple hooks for different threads.
To remove a hook call Thread::remove_hook.
Sourcepub fn remove_hook(&self)
Available on non-crate feature luau only.
pub fn remove_hook(&self)
luau only.Removes any hook function from this thread.
Sourcepub fn reset(&self, func: Function) -> Result<()>
pub fn reset(&self, func: Function) -> Result<()>
Resets a thread
In Lua 5.4: cleans its call stack and closes all pending to-be-closed variables. Returns a error in case of either the original error that stopped the thread or errors in closing methods.
In Luau: resets to the initial state of a newly created Lua thread. Lua threads in arbitrary states (like yielded or errored) can be reset properly.
Other Lua versions can reset only new or finished threads.
Sets a Lua function for the thread afterwards.
Sourcepub fn into_async<R>(self, args: impl IntoLuaMulti) -> Result<AsyncThread<R>>where
R: FromLuaMulti,
Available on crate feature async only.
pub fn into_async<R>(self, args: impl IntoLuaMulti) -> Result<AsyncThread<R>>where
R: FromLuaMulti,
async only.Converts Thread to an AsyncThread which implements Future and Stream traits.
Only resumable threads can be converted to AsyncThread.
args are pushed to the thread stack and will be used when the thread is resumed.
The object calls resume while polling and also allow to run Rust futures
to completion using an executor.
Using AsyncThread as a Stream allow to iterate through coroutine.yield
values whereas Future version discards that values and poll until the final
one (returned from the thread function).
§Examples
use futures_util::stream::TryStreamExt;
let thread: Thread = lua.load(r#"
coroutine.create(function (sum)
for i = 1,10 do
sum = sum + i
coroutine.yield(sum)
end
return sum
end)
"#).eval()?;
let mut stream = thread.into_async::<i64>(1)?;
let mut sum = 0;
while let Some(n) = stream.try_next().await? {
sum += n;
}
assert_eq!(sum, 286);
Sourcepub fn sandbox(&self) -> Result<()>
Available on crate feature luau only.
pub fn sandbox(&self) -> Result<()>
luau only.Enables sandbox mode on this thread.
Under the hood replaces the global environment table with a new table, that performs writes locally and proxies reads to caller’s global environment.
This mode ideally should be used together with the global sandbox mode [Lua::sandbox].
Please note that Luau links environment table with chunk when loading it into Lua state. Therefore you need to load chunks into a thread to link with the thread environment.
§Examples
let lua = Lua::new();
let thread = lua.create_thread(lua.create_function(|lua2, ()| {
lua2.load("var = 123").exec()?;
assert_eq!(lua2.globals().get::<u32>("var")?, 123);
Ok(())
})?)?;
thread.sandbox()?;
thread.resume::<()>(())?;
// The global environment should be unchanged
assert_eq!(lua.globals().get::<Option<u32>>("var")?, None);
Sourcepub fn to_pointer(&self) -> *const c_void
pub fn to_pointer(&self) -> *const c_void
Converts this thread to a generic C pointer.
There is no way to convert the pointer back to its original value.
Typically this function is used only for hashing and debug information.
Trait Implementations§
impl Send for Thread
impl Sync for Thread
Auto Trait Implementations§
impl Freeze for Thread
impl !RefUnwindSafe for Thread
impl Unpin for Thread
impl !UnwindSafe for Thread
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FromLuaMulti for Twhere
T: FromLua,
impl<T> FromLuaMulti for Twhere
T: FromLua,
Source§fn from_lua_multi(values: MultiValue, lua: &Lua) -> Result<T, Error>
fn from_lua_multi(values: MultiValue, lua: &Lua) -> Result<T, Error>
fn from_lua_args( args: MultiValue, i: usize, to: Option<&str>, lua: &Lua, ) -> Result<T, Error>
unsafe fn from_stack_multi(nvals: i32, lua: &RawLua) -> Result<T, Error>
unsafe fn from_stack_args( nargs: i32, i: usize, to: Option<&str>, lua: &RawLua, ) -> Result<T, Error>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more