mlua_extras/extras/macros.rs
1/// Write a lua function similar to Rust's syntax
2///
3/// # Example
4///
5/// ```
6/// use mlua::Lua;
7///
8/// let lua = Lua::new();
9/// lua.create_function(|lua, ()| Ok(()))
10/// ```
11///
12/// vs
13///
14/// ```
15/// use mlua_extras::{mlua::Lua, function};
16///
17/// let lua = Lua::new();
18/// function! {
19/// lua fn name(lua) {
20/// Ok(())
21/// }
22/// }
23/// ```
24///
25/// It can also be used to asssign functions to nested tables. This requires the `LuaExtras` crate
26/// when you start with lua as the source, and the `Require` trait when using any other table as
27/// the source.
28///
29/// ```
30/// use mlua::{Lua, Table};
31///
32/// let lua = Lua::new();
33/// lua.globals().get::<_, Table>("nested")?.set("name", lua.create_function(|lua, ()| Ok(()))?)?;
34///
35/// let nested = lua.globals().get::<_, Table>("deep")?.get::<_, Table>("nested");
36/// nested.set("name", lua.create_function(|lua, ()| Ok(())))?;
37/// ```
38///
39/// vs
40///
41/// ```
42/// use mlua_extras::{
43/// mlua::{Lua, Table},
44/// extras::{LuaExtras, Require},
45/// };
46///
47/// let lua = Lua::new();
48/// function! {
49/// lua fn lua::nested.name(lua) {
50/// Ok(())
51/// }
52/// }
53///
54/// let nested = lua.globals().get::<_, Table>("deep")?;
55/// function! {
56/// lua fn deep::nested.name(lua) {
57/// Ok(())
58/// }
59/// }
60/// ```
61#[macro_export]
62macro_rules! function {
63 {
64 $(#[$($attr: tt)*])*
65 $lua: ident fn $name: ident(
66 $l: ident $(: $lty: ty)?
67 $(, $arg: ident : $aty: ty)*
68 ) $(-> $ret: ty)? {
69 $($body: tt)*
70 }
71 } => {
72 $lua.create_function(|$l $(: $lty)?, ($($arg,)*): ($($aty,)*)| $(-> $ret)? {
73 $($body)*
74 })
75 };
76 {
77 $(#[$($attr: tt)*])*
78 $lua: ident fn $source: ident $(::$inner: ident)* . $name: ident(
79 $l: ident $(: $lty: ty)?
80 $(, $arg: ident : $aty: ty)*
81 ) $(-> $ret: ty)? {
82 $($body: tt)*
83 }
84 } => {
85 {
86 match $source.require::<mlua::Table>(stringify!($($inner.)*)) $(-> $ret: ty)? {
87 Ok(table) => match $lua.create_function(|$l$(: $lty)?, ($($arg,)*): ($($aty,)*)| $(-> $ret)? {
88 $($body)*
89 }) {
90 Ok(fun) => table.set(stringify!($name), fun),
91 Err(err) => Err(err)
92 }
93 Err(err) => Err(err)
94 }
95 }
96 };
97}