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:
Alex Orlenko
2022-12-22 16:24:35 +00:00
parent 9d28b790e7
commit 1d4a135e8e
4 changed files with 140 additions and 1 deletions
+14
View File
@@ -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();
+33
View File
@@ -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(())
}