mlua/tests/function.rs

92 lines
1.9 KiB
Rust
Raw Normal View History

use mlua::{Function, Lua, Result, String};
2018-02-09 22:52:05 -06:00
#[test]
2019-09-28 09:23:17 -05:00
fn test_function() -> Result<()> {
2019-10-14 16:21:30 -05:00
let lua = Lua::new();
2019-09-28 09:23:17 -05:00
2018-02-09 22:52:05 -06:00
let globals = lua.globals();
2019-09-28 09:23:17 -05:00
lua.load(
2018-02-09 22:52:05 -06:00
r#"
function concat(arg1, arg2)
return arg1 .. arg2
end
"#,
2019-09-27 11:38:24 -05:00
)
2019-09-28 09:23:17 -05:00
.exec()?;
let concat = globals.get::<_, Function>("concat")?;
assert_eq!(concat.call::<_, String>(("foo", "bar"))?, "foobar");
2018-02-09 22:52:05 -06:00
2019-09-28 09:23:17 -05:00
Ok(())
2018-02-09 22:52:05 -06:00
}
#[test]
2019-09-28 09:23:17 -05:00
fn test_bind() -> Result<()> {
2019-10-14 16:21:30 -05:00
let lua = Lua::new();
2019-09-28 09:23:17 -05:00
2018-02-09 22:52:05 -06:00
let globals = lua.globals();
2019-09-28 09:23:17 -05:00
lua.load(
2018-02-09 22:52:05 -06:00
r#"
function concat(...)
local res = ""
for _, s in pairs({...}) do
res = res..s
end
return res
end
"#,
2019-09-27 11:38:24 -05:00
)
2019-09-28 09:23:17 -05:00
.exec()?;
2018-02-09 22:52:05 -06:00
2019-09-28 09:23:17 -05:00
let mut concat = globals.get::<_, Function>("concat")?;
concat = concat.bind("foo")?;
concat = concat.bind("bar")?;
concat = concat.bind(("baz", "baf"))?;
2018-02-09 22:52:05 -06:00
assert_eq!(
2019-09-28 09:23:17 -05:00
concat.call::<_, String>(("hi", "wut"))?,
2018-02-09 22:52:05 -06:00
"foobarbazbafhiwut"
);
2019-09-28 09:23:17 -05:00
Ok(())
2018-02-09 22:52:05 -06:00
}
#[test]
2019-09-28 09:23:17 -05:00
fn test_rust_function() -> Result<()> {
2019-10-14 16:21:30 -05:00
let lua = Lua::new();
2019-09-28 09:23:17 -05:00
2018-02-09 22:52:05 -06:00
let globals = lua.globals();
2019-09-28 09:23:17 -05:00
lua.load(
2018-02-09 22:52:05 -06:00
r#"
function lua_function()
return rust_function()
end
-- Test to make sure chunk return is ignored
return 1
"#,
2019-09-27 11:38:24 -05:00
)
2019-09-28 09:23:17 -05:00
.exec()?;
let lua_function = globals.get::<_, Function>("lua_function")?;
let rust_function = lua.create_function(|_, ()| Ok("hello"))?;
2018-02-09 22:52:05 -06:00
2019-09-28 09:23:17 -05:00
globals.set("rust_function", rust_function)?;
assert_eq!(lua_function.call::<_, String>(())?, "hello");
2018-02-09 22:52:05 -06:00
2019-09-28 09:23:17 -05:00
Ok(())
2018-02-09 22:52:05 -06:00
}
#[test]
fn test_dump() -> Result<()> {
let lua = unsafe { Lua::unsafe_new() };
let concat_lua = lua
.load(r#"function(arg1, arg2) return arg1 .. arg2 end"#)
.eval::<Function>()?;
let concat = lua.load(&concat_lua.dump(false)?).into_function()?;
assert_eq!(concat.call::<_, String>(("foo", "bar"))?, "foobar");
Ok(())
}