#![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", allow(unused_attributes) )] extern "system" {} use mlua::{Error, Function, Lua, Result, String}; #[test] fn test_function() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); lua.load( r#" function concat(arg1, arg2) return arg1 .. arg2 end "#, ) .exec()?; let concat = globals.get::<_, Function>("concat")?; assert_eq!(concat.call::<_, String>(("foo", "bar"))?, "foobar"); Ok(()) } #[test] fn test_bind() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); lua.load( r#" function concat(...) local res = "" for _, s in pairs({...}) do res = res..s end return res end "#, ) .exec()?; let mut concat = globals.get::<_, Function>("concat")?; concat = concat.bind("foo")?; concat = concat.bind("bar")?; concat = concat.bind(("baz", "baf"))?; assert_eq!( concat.call::<_, String>(("hi", "wut"))?, "foobarbazbafhiwut" ); Ok(()) } #[test] fn test_rust_function() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); lua.load( r#" function lua_function() return rust_function() end -- Test to make sure chunk return is ignored return 1 "#, ) .exec()?; let lua_function = globals.get::<_, Function>("lua_function")?; let rust_function = lua.create_function(|_, ()| Ok("hello"))?; globals.set("rust_function", rust_function)?; assert_eq!(lua_function.call::<_, String>(())?, "hello"); Ok(()) } #[test] fn test_dump() -> Result<()> { let lua = unsafe { Lua::unsafe_new() }; let concat_tmp = lua .load(r#"function(arg1, arg2) return arg1 .. arg2 end"#) .eval::()?; let concat_bytecode = concat_tmp.dump(false)?; let concat = lua.load(&concat_bytecode).into_function()?; assert_eq!(concat.call::<_, String>(("foo", "bar"))?, "foobar"); let lua = Lua::new(); match lua.load(&concat_bytecode).exec() { Ok(_) => panic!("expected SyntaxError, got no error"), Err(Error::SyntaxError { message: msg, .. }) => { assert!(msg.contains("attempt to load a binary chunk")) } Err(e) => panic!("expected SyntaxError, got {:?}", e), } Ok(()) }