mlua/tests/function.rs

89 lines
1.9 KiB
Rust
Raw Normal View History

2019-10-16 05:56:44 -04:00
#![cfg_attr(
all(feature = "luajit", target_os = "macos", target_arch = "x86_64"),
feature(link_args)
)]
#[cfg_attr(
all(feature = "luajit", target_os = "macos", target_arch = "x86_64"),
link_args = "-pagezero_size 10000 -image_base 100000000"
)]
extern "system" {}
2019-10-14 17:21:30 -04:00
use mlua::{Function, Lua, Result, String};
2018-02-09 23:52:05 -05:00
#[test]
2019-09-28 10:23:17 -04:00
fn test_function() -> Result<()> {
2019-10-14 17:21:30 -04:00
let lua = Lua::new();
2019-09-28 10:23:17 -04:00
2018-02-09 23:52:05 -05:00
let globals = lua.globals();
2019-09-28 10:23:17 -04:00
lua.load(
2018-02-09 23:52:05 -05:00
r#"
function concat(arg1, arg2)
return arg1 .. arg2
end
"#,
2019-09-27 12:38:24 -04:00
)
2019-09-28 10:23:17 -04:00
.exec()?;
let concat = globals.get::<_, Function>("concat")?;
assert_eq!(concat.call::<_, String>(("foo", "bar"))?, "foobar");
2018-02-09 23:52:05 -05:00
2019-09-28 10:23:17 -04:00
Ok(())
2018-02-09 23:52:05 -05:00
}
#[test]
2019-09-28 10:23:17 -04:00
fn test_bind() -> Result<()> {
2019-10-14 17:21:30 -04:00
let lua = Lua::new();
2019-09-28 10:23:17 -04:00
2018-02-09 23:52:05 -05:00
let globals = lua.globals();
2019-09-28 10:23:17 -04:00
lua.load(
2018-02-09 23:52:05 -05:00
r#"
function concat(...)
local res = ""
for _, s in pairs({...}) do
res = res..s
end
return res
end
"#,
2019-09-27 12:38:24 -04:00
)
2019-09-28 10:23:17 -04:00
.exec()?;
2018-02-09 23:52:05 -05:00
2019-09-28 10:23:17 -04:00
let mut concat = globals.get::<_, Function>("concat")?;
concat = concat.bind("foo")?;
concat = concat.bind("bar")?;
concat = concat.bind(("baz", "baf"))?;
2018-02-09 23:52:05 -05:00
assert_eq!(
2019-09-28 10:23:17 -04:00
concat.call::<_, String>(("hi", "wut"))?,
2018-02-09 23:52:05 -05:00
"foobarbazbafhiwut"
);
2019-09-28 10:23:17 -04:00
Ok(())
2018-02-09 23:52:05 -05:00
}
#[test]
2019-09-28 10:23:17 -04:00
fn test_rust_function() -> Result<()> {
2019-10-14 17:21:30 -04:00
let lua = Lua::new();
2019-09-28 10:23:17 -04:00
2018-02-09 23:52:05 -05:00
let globals = lua.globals();
2019-09-28 10:23:17 -04:00
lua.load(
2018-02-09 23:52:05 -05:00
r#"
function lua_function()
return rust_function()
end
-- Test to make sure chunk return is ignored
return 1
"#,
2019-09-27 12:38:24 -04:00
)
2019-09-28 10:23:17 -04:00
.exec()?;
let lua_function = globals.get::<_, Function>("lua_function")?;
let rust_function = lua.create_function(|_, ()| Ok("hello"))?;
2018-02-09 23:52:05 -05:00
2019-09-28 10:23:17 -04:00
globals.set("rust_function", rust_function)?;
assert_eq!(lua_function.call::<_, String>(())?, "hello");
2018-02-09 23:52:05 -05:00
2019-09-28 10:23:17 -04:00
Ok(())
2018-02-09 23:52:05 -05:00
}