mirror of
https://github.com/mlua-rs/mlua
synced 2026-06-08 16:05:43 +00:00
Add Function::wrap/Function::wrap_mut/Function::wrap_async to wrap functions into a type that implements IntoLua trait.
This is useful to avoid calling `lua.create_function*` every time when `Function` handle is needed.
This commit is contained in:
@@ -30,6 +30,20 @@ async fn test_async_function() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[tokio::test]
|
||||
async fn test_async_function_wrap() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let f = Function::wrap_async(|_, s: String| async move { Ok(s) });
|
||||
lua.globals().set("f", f)?;
|
||||
|
||||
let res: String = lua.load(r#"f("hello")"#).eval_async().await?;
|
||||
assert_eq!(res, "hello");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_async_sleep() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
@@ -167,3 +167,36 @@ fn test_function_info() -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "unstable")]
|
||||
#[test]
|
||||
fn test_function_wrap() -> Result<()> {
|
||||
use mlua::Error;
|
||||
|
||||
let lua = Lua::new();
|
||||
|
||||
lua.globals()
|
||||
.set("f", Function::wrap(|_, s: String| Ok(s)))?;
|
||||
lua.load(r#"assert(f("hello") == "hello")"#).exec().unwrap();
|
||||
|
||||
let mut _i = false;
|
||||
lua.globals().set(
|
||||
"f",
|
||||
Function::wrap_mut(move |lua, ()| {
|
||||
_i = true;
|
||||
lua.globals().get::<_, Function>("f")?.call::<_, ()>(())
|
||||
}),
|
||||
)?;
|
||||
match lua.globals().get::<_, Function>("f")?.call::<_, ()>(()) {
|
||||
Err(Error::CallbackError { ref cause, .. }) => match *cause.as_ref() {
|
||||
Error::CallbackError { ref cause, .. } => match *cause.as_ref() {
|
||||
Error::RecursiveMutCallback { .. } => {}
|
||||
ref other => panic!("incorrect result: {other:?}"),
|
||||
},
|
||||
ref other => panic!("incorrect result: {other:?}"),
|
||||
},
|
||||
other => panic!("incorrect result: {other:?}"),
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user