lua_wrapper/
lib.rs

1/// Allows to easily bind rust functions to your Lua code
2///
3/// **THIS USES UNWRAPS INTERNALLY, SO IT MIGHT PANIC**
4///
5/// # Arguments
6///
7/// * `lua_inst` - Your lua instance, create with rlua::Lua::new()
8/// * `to_call` - The rust function you want to call, the lua function will have the same name
9/// * `argname` - Optional parameter for functions with parameters: Specifies the name of the arg
10/// * `argtype` - Optional parameter for functions with parameters: Specifies the type of the arg
11///
12/// # Example
13///
14/// Rust setup:
15///
16/// ```rust
17/// let lua_inst = rlua::Lua::new();
18/// make_lua_fn!(lua_inst, print_hello);
19/// make_lua_fn!(lua_inst, print_arg, (arg, u32));
20/// make_lua_fn!(lua_inst, print_multi_args, (arg, u32), (arg2, f32));
21/// make_lua_fn!(lua_inst, print_multi_args_names, (argNameCanBeAnything, u32), (arg2, f32));
22/// ```
23///
24/// Lua usage:
25///
26/// ```lua
27/// print_hello()
28/// print_arg(12)
29/// print_multi_args(12, 4.0)
30/// ```
31#[macro_export]
32macro_rules! make_lua_fn {
33    ($lua_inst:ident, $to_call: ident, $(
34        ($argname: ident, $argtype: ty))
35        ,
36        *
37        ) => {
38        let tmp = $lua_inst
39            .create_function(|_, ($($argname,)*): ($($argtype,)*)| {
40                Ok($to_call($($argname,)*))
41                })
42            .unwrap();
43        $lua_inst.globals().set(stringify!($to_call), tmp).unwrap();
44    };
45
46    ($lua_inst:ident, $to_call: ident) => {
47        let tmp = $lua_inst
48            .create_function(move |_, ()| Ok($to_call()))
49            .unwrap();
50        $lua_inst.globals().set(stringify!($to_call), tmp).unwrap();
51    };
52}
53
54#[cfg(test)]
55mod tests {
56    use rlua::Lua;
57    #[test]
58    fn test_functions() {
59        let lua = setup_lua();
60        let lua_str = r#"
61        print_hello()
62        print(get_random_number())
63        print_arg(14)
64        print_multi_args(14, 4.4)
65        "#;
66        lua.eval::<_, ()>(lua_str, None).unwrap();
67    }
68
69    fn setup_lua() -> crate::Lua {
70        let lua_inst = crate::Lua::new();
71        make_lua_fn!(lua_inst, print_hello);
72        make_lua_fn!(lua_inst, get_random_number);
73        make_lua_fn!(lua_inst, print_arg, (arg, u32));
74        make_lua_fn!(lua_inst, print_multi_args, (arg, u32), (arg2, f32));
75        lua_inst
76    }
77
78    fn print_hello() {
79        println!("Hello from Rust");
80    }
81
82    fn get_random_number() -> u32 {
83        println!("Returning 4");
84        4
85    }
86
87    fn print_arg(data: u32) {
88        println!("Got single arg {}", data);
89    }
90
91    fn print_multi_args(data: u32, data2: f32) {
92        println!("Got multiple args {} and {}", data, data2);
93    }
94
95}