summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorrise0chen <rise0chen@163.com>2022-11-29 10:46:51 +0800
committerAlex Orlenko <zxteam@protonmail.com>2022-12-18 00:35:41 +0000
commitb532f866742b16f5d54715678ddf1c93e0340ff6 (patch)
treec927e093bf7c5777c91e24ec5e91affa21cf1d2b
parentc44463f030f592fa4bc0feaf66c76d467ae01919 (diff)
downloadmlua-b532f866742b16f5d54715678ddf1c93e0340ff6.zip
feat: Support custom name of `lua_module`
-rw-r--r--mlua_derive/src/lib.rs42
-rw-r--r--tests/module/src/lib.rs2
2 files changed, 35 insertions, 9 deletions
diff --git a/mlua_derive/src/lib.rs b/mlua_derive/src/lib.rs
index afa8b54..76fb415 100644
--- a/mlua_derive/src/lib.rs
+++ b/mlua_derive/src/lib.rs
@@ -1,7 +1,7 @@
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use quote::quote;
-use syn::{parse_macro_input, AttributeArgs, Error, ItemFn};
+use syn::{parse_macro_input, AttributeArgs, ItemFn, Lit, Meta, NestedMeta};
#[cfg(feature = "macros")]
use {
@@ -9,19 +9,45 @@ use {
proc_macro_error::proc_macro_error,
};
+#[derive(Default)]
+struct ModuleArgs {
+ name: Option<Ident>,
+}
+impl ModuleArgs {
+ fn parse(attr: AttributeArgs) -> Self {
+ let mut ret = Self::default();
+
+ for arg in attr {
+ match arg {
+ NestedMeta::Meta(Meta::NameValue(meta)) => {
+ if meta.path.segments.last().unwrap().ident == "name" {
+ if let Lit::Str(val) = meta.lit {
+ if let Ok(val) = val.parse() {
+ ret.name = Some(val);
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ ret
+ }
+}
+
#[proc_macro_attribute]
pub fn lua_module(attr: TokenStream, item: TokenStream) -> TokenStream {
let args = parse_macro_input!(attr as AttributeArgs);
+ let args = ModuleArgs::parse(args);
let func = parse_macro_input!(item as ItemFn);
- if !args.is_empty() {
- let err = Error::new(Span::call_site(), "the macro does not support arguments")
- .to_compile_error();
- return err.into();
- }
-
let func_name = func.sig.ident.clone();
- let ext_entrypoint_name = Ident::new(&format!("luaopen_{}", func_name), Span::call_site());
+ let module_name = if let Some(name) = args.name {
+ name
+ } else {
+ func_name.clone()
+ };
+ let ext_entrypoint_name = Ident::new(&format!("luaopen_{}", module_name), Span::call_site());
let wrapped = quote! {
::mlua::require_module_feature!();
diff --git a/tests/module/src/lib.rs b/tests/module/src/lib.rs
index fdaf171..c624078 100644
--- a/tests/module/src/lib.rs
+++ b/tests/module/src/lib.rs
@@ -12,7 +12,7 @@ fn check_userdata(_: &Lua, ud: MyUserData) -> LuaResult<i32> {
Ok(ud.0)
}
-#[mlua::lua_module]
+#[mlua::lua_module(name = "rust_module_first")]
fn rust_module(lua: &Lua) -> LuaResult<LuaTable> {
let exports = lua.create_table()?;
exports.set("sum", lua.create_function(sum)?)?;