From 69dceceef5287194b12614582dab6a42d4d43fcd Mon Sep 17 00:00:00 2001 From: Tin Date: Sat, 18 Nov 2023 23:56:10 +0100 Subject: [PATCH 01/18] Implement nested composition of FromLuaMulti Signed-off-by: Tin --- src/context.rs | 31 +++++++++++++----- src/function.rs | 3 +- src/multi.rs | 84 +++++++++++++++++++++++++++++++++++-------------- src/scope.rs | 27 ++++++++++------ src/thread.rs | 3 +- src/value.rs | 14 ++++++++- 6 files changed, 120 insertions(+), 42 deletions(-) diff --git a/src/context.rs b/src/context.rs index 5f5ff0f0..d8cb5648 100644 --- a/src/context.rs +++ b/src/context.rs @@ -179,7 +179,8 @@ impl<'lua> Context<'lua> { F: 'static + Send + Fn(Context<'lua>, A) -> Result, { self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + func(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })) } @@ -365,8 +366,12 @@ impl<'lua> Context<'lua> { } /// Converts a `MultiValue` instance into a value that implements `FromLuaMulti`. - pub fn unpack_multi>(self, value: MultiValue<'lua>) -> Result { - T::from_lua_multi(value, self) + pub fn unpack_multi>( + self, + value: MultiValue<'lua>, + consumed: &mut usize, + ) -> Result { + T::from_lua_multi(value, self, consumed) } /// Set a value in the Lua registry based on a string name. @@ -1131,7 +1136,9 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { if let Some(front) = args.pop_front() { let userdata = AnyUserData::from_lua(front, lua)?; let userdata = userdata.borrow::()?; - method(lua, &userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + method(lua, &userdata, A::from_lua_multi(args, lua, &mut consumed)?)? + .to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1156,7 +1163,13 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let mut method = method .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - (&mut *method)(lua, &mut userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + (&mut *method)( + lua, + &mut userdata, + A::from_lua_multi(args, lua, &mut consumed)?, + )? + .to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1173,7 +1186,10 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { R: ToLuaMulti<'lua>, F: 'static + Send + Fn(Context<'lua>, A) -> Result, { - Box::new(move |lua, args| function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua)) + Box::new(move |lua, args| { + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + }) } fn box_function_mut(function: F) -> Callback<'lua, 'static> @@ -1187,7 +1203,8 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let function = &mut *function .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) }) } } diff --git a/src/function.rs b/src/function.rs index cb98b756..fd745880 100644 --- a/src/function.rs +++ b/src/function.rs @@ -88,7 +88,8 @@ impl<'lua> Function<'lua> { ffi::lua_pop(lua.state, 1); results }; - R::from_lua_multi(results, lua) + let mut consumed = 0; + R::from_lua_multi(results, lua, &mut consumed) } /// Returns a function that, when called, calls `self`, passing `args` as the first set of diff --git a/src/multi.rs b/src/multi.rs index 9a050b04..92e0708e 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -33,8 +33,18 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T { } impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T { - fn from_lua_multi(mut values: MultiValue<'lua>, lua: Context<'lua>) -> Result { - Ok(T::from_lua(values.pop_front().unwrap_or(Nil), lua)?) + fn from_lua_multi( + mut values: MultiValue<'lua>, + lua: Context<'lua>, + consumed: &mut usize, + ) -> Result { + match values.pop_front() { + Some(it) => { + *consumed += 1; + Ok(T::from_lua(it, lua)?) + } + None => Ok(T::from_lua(Nil, lua)?), + } } } @@ -45,7 +55,12 @@ impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { } impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { - fn from_lua_multi(values: MultiValue<'lua>, _: Context<'lua>) -> Result { + fn from_lua_multi( + values: MultiValue<'lua>, + _: Context<'lua>, + consumed: &mut usize, + ) -> Result { + *consumed += values.len(); Ok(values) } } @@ -85,6 +100,11 @@ impl Variadic { pub fn new() -> Variadic { Variadic(Vec::new()) } + + #[inline] + pub fn len(&self) -> usize { + self.0.len() + } } impl Default for Variadic { @@ -129,12 +149,20 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic { } impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic { - fn from_lua_multi(values: MultiValue<'lua>, lua: Context<'lua>) -> Result { - values + fn from_lua_multi( + values: MultiValue<'lua>, + lua: Context<'lua>, + consumed: &mut usize, + ) -> Result { + let result = values .into_iter() .map(|e| T::from_lua(e, lua)) .collect::>>() - .map(Variadic) + .map(Variadic); + if let Ok(result) = &result { + *consumed += result.len(); + } + result } } @@ -147,38 +175,48 @@ macro_rules! impl_tuple { } impl<'lua> FromLuaMulti<'lua> for () { - fn from_lua_multi(_: MultiValue, _: Context<'lua>) -> Result { + fn from_lua_multi(_: MultiValue, _: Context<'lua>, _: &mut usize) -> Result { Ok(()) } } ); - ($last:ident $($name:ident)*) => ( - impl<'lua, $($name,)* $last> ToLuaMulti<'lua> for ($($name,)* $last,) - where $($name: ToLua<'lua>,)* - $last: ToLuaMulti<'lua> + ($($name:ident)+) => ( + impl<'lua, $($name),*> ToLuaMulti<'lua> for ($($name,)*) + where $($name: ToLuaMulti<'lua>),* { #[allow(unused_mut)] #[allow(non_snake_case)] fn to_lua_multi(self, lua: Context<'lua>) -> Result> { - let ($($name,)* $last,) = self; + let ($($name,)*) = self; - let mut results = $last.to_lua_multi(lua)?; - push_reverse!(results, $($name.to_lua(lua)?,)*); + let mut results = MultiValue::new(); + push_reverse!(results, $($name.to_lua_multi(lua)?,)*); Ok(results) } } - impl<'lua, $($name,)* $last> FromLuaMulti<'lua> for ($($name,)* $last,) - where $($name: FromLua<'lua>,)* - $last: FromLuaMulti<'lua> + impl<'lua, $($name),*> FromLuaMulti<'lua> for ($($name,)*) + where $($name: FromLuaMulti<'lua>),* { #[allow(unused_mut)] #[allow(non_snake_case)] - fn from_lua_multi(mut values: MultiValue<'lua>, lua: Context<'lua>) -> Result { - $(let $name = values.pop_front().unwrap_or(Nil);)* - let $last = FromLuaMulti::from_lua_multi(values, lua)?; - Ok(($(FromLua::from_lua($name, lua)?,)* $last,)) + fn from_lua_multi(mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize) -> Result { + $( + let $name = { + let mut consumed = 0; + let it = match FromLuaMulti::from_lua_multi(values.clone(), lua, &mut consumed) { + Ok(it) => it, + Err(err) => { + return Err(err); + } + }; + *total += consumed; + values.drop_front(consumed); + it + }; + )* + Ok(($($name,)*)) } } ); @@ -187,11 +225,11 @@ macro_rules! impl_tuple { macro_rules! push_reverse { ($multi_value:expr, $first:expr, $($rest:expr,)*) => ( push_reverse!($multi_value, $($rest,)*); - $multi_value.push_front($first); + $multi_value.push_front_many($first); ); ($multi_value:expr, $first:expr) => ( - $multi_value.push_front($first); + $multi_value.push_front_many($first); ); ($multi_value:expr,) => (); diff --git a/src/scope.rs b/src/scope.rs index d6f16df1..048bab0b 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -64,7 +64,8 @@ impl<'lua, 'scope> Scope<'lua, 'scope> { // scope, and owned inside the callback itself. unsafe { self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + func(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })) } } @@ -381,7 +382,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -396,7 +398,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -411,7 +414,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -426,7 +430,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -440,7 +445,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -454,7 +460,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -468,7 +475,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } @@ -482,7 +490,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + let mut consumed = 0; + function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) })), )); } diff --git a/src/thread.rs b/src/thread.rs index 0bd9a012..2464ad0e 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -119,7 +119,8 @@ impl<'lua> Thread<'lua> { } results }; - R::from_lua_multi(results, lua) + let mut consumed = 0; + R::from_lua_multi(results, lua, &mut consumed) } /// Gets the status of the thread. diff --git a/src/value.rs b/src/value.rs index 3c9862f3..2b2f2f2a 100644 --- a/src/value.rs +++ b/src/value.rs @@ -142,10 +142,18 @@ impl<'lua> MultiValue<'lua> { self.0.push(value); } + pub(crate) fn push_front_many(&mut self, values: Self) { + self.0.extend(values.into_iter()); + } + pub(crate) fn pop_front(&mut self) -> Option> { self.0.pop() } + pub(crate) fn drop_front(&mut self, count: usize) { + self.0.drain(self.0.len() - count..).count(); + } + pub fn len(&self) -> usize { self.0.len() } @@ -179,5 +187,9 @@ pub trait FromLuaMulti<'lua>: Sized { /// values should be ignored. This reflects the semantics of Lua when calling a function or /// assigning values. Similarly, if not enough values are given, conversions should assume that /// any missing values are nil. - fn from_lua_multi(values: MultiValue<'lua>, lua: Context<'lua>) -> Result; + fn from_lua_multi( + values: MultiValue<'lua>, + lua: Context<'lua>, + consumed: &mut usize, + ) -> Result; } From 16d519bc9843c26825ceecd4fe31351c3f373a15 Mon Sep 17 00:00:00 2001 From: Tin Date: Sun, 19 Nov 2023 00:33:27 +0100 Subject: [PATCH 02/18] Make Variadic stop collecting on error Signed-off-by: Tin --- src/multi.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/multi.rs b/src/multi.rs index 92e0708e..a664669a 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -157,12 +157,11 @@ impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic { let result = values .into_iter() .map(|e| T::from_lua(e, lua)) - .collect::>>() - .map(Variadic); - if let Ok(result) = &result { - *consumed += result.len(); - } - result + .take_while(|it| it.is_ok()) + .filter_map(|it| it.ok()) + .collect::>(); + *consumed += result.len(); + Ok(Variadic(result)) } } From ce0232e3441c19b6067c9d7053e08c4c8383e6be Mon Sep 17 00:00:00 2001 From: Tin Date: Sun, 19 Nov 2023 01:04:11 +0100 Subject: [PATCH 03/18] Allow FromLuaMulti values in Variadic Signed-off-by: Tin --- src/multi.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/multi.rs b/src/multi.rs index a664669a..2011eab3 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -148,19 +148,20 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic { } } -impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic { +impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { fn from_lua_multi( - values: MultiValue<'lua>, + mut values: MultiValue<'lua>, lua: Context<'lua>, - consumed: &mut usize, + total: &mut usize, ) -> Result { - let result = values - .into_iter() - .map(|e| T::from_lua(e, lua)) - .take_while(|it| it.is_ok()) - .filter_map(|it| it.ok()) - .collect::>(); - *consumed += result.len(); + let mut consumed = 0; + let mut result = Vec::new(); + while let Ok(it) = T::from_lua_multi(values.clone(), lua, &mut consumed) { + result.push(it); + values.drop_front(consumed); + *total += consumed; + consumed = 0; + } Ok(Variadic(result)) } } From b61c7032890e612fbc79c6ec9faeb22c78f4eb16 Mon Sep 17 00:00:00 2001 From: Tin Date: Sun, 19 Nov 2023 01:11:38 +0100 Subject: [PATCH 04/18] Support Option values Signed-off-by: Tin --- src/conversion.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/conversion.rs b/src/conversion.rs index 966c08e2..5f29b56f 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -16,6 +16,7 @@ use crate::thread::Thread; use crate::types::{LightUserData, Number}; use crate::userdata::{AnyUserData, UserData}; use crate::value::{FromLua, Nil, ToLua, Value}; +use crate::FromLuaMulti; impl<'lua> ToLua<'lua> for Value<'lua> { fn to_lua(self, _: Context<'lua>) -> Result> { @@ -507,11 +508,15 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { } } -impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option { - fn from_lua(value: Value<'lua>, lua: Context<'lua>) -> Result { - match value { - Nil => Ok(None), - value => Ok(Some(T::from_lua(value, lua)?)), +impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Option { + fn from_lua_multi( + values: crate::MultiValue<'lua>, + lua: Context<'lua>, + consumed: &mut usize, + ) -> Result { + match T::from_lua_multi(values, lua, consumed) { + Ok(it) => Ok(Some(it)), + Err(_) => Ok(None), } } } From 72b6a0ce683d34bcf26bd53e0f79f045cb2b4dfa Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 13:32:16 +0100 Subject: [PATCH 05/18] Support FromLuaMulti from Vec Old behavior works the same, this addition allows additionally passing types that specialize FromLuaMulti which would then cause the Table entries to be able to get collected from multiple consecutive values in table such as: { a, { b.a, b.b }, c, d, { e.a, e.b } } If `b` errors, error is on `b` not being T. Signed-off-by: Tin --- src/conversion.rs | 25 +++++++++++++++++++++---- src/value.rs | 2 +- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/conversion.rs b/src/conversion.rs index 5f29b56f..c6a1eeb1 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -16,7 +16,7 @@ use crate::thread::Thread; use crate::types::{LightUserData, Number}; use crate::userdata::{AnyUserData, UserData}; use crate::value::{FromLua, Nil, ToLua, Value}; -use crate::FromLuaMulti; +use crate::{FromLuaMulti, MultiValue}; impl<'lua> ToLua<'lua> for Value<'lua> { fn to_lua(self, _: Context<'lua>) -> Result> { @@ -441,10 +441,27 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Vec { } } -impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Vec { - fn from_lua(value: Value<'lua>, _: Context<'lua>) -> Result { +impl<'lua, T: FromLuaMulti<'lua>> FromLua<'lua> for Vec { + fn from_lua(value: Value<'lua>, lua: Context<'lua>) -> Result { if let Value::Table(table) = value { - table.sequence_values().collect() + let mut values: MultiValue = MultiValue( + table + .sequence_values::() + .filter_map(Result::ok) // Every value in Table is always a Value + .collect(), + ); + let mut result = Vec::new(); + let mut consumed = 0; + while values.len() > 0 { + match T::from_lua_multi(values.clone(), lua, &mut consumed) { + Ok(it) => { + result.push(it); + values.drop_front(consumed); + } + Err(err) => return Err(err), + } + } + Ok(result) } else { Err(Error::FromLuaConversionError { from: value.type_name(), diff --git a/src/value.rs b/src/value.rs index 2b2f2f2a..840129d7 100644 --- a/src/value.rs +++ b/src/value.rs @@ -83,7 +83,7 @@ pub trait FromLua<'lua>: Sized { /// Multiple Lua values used for both argument passing and also for multiple return values. #[derive(Debug, Clone)] -pub struct MultiValue<'lua>(Vec>); +pub struct MultiValue<'lua>(pub(crate) Vec>); impl<'lua> MultiValue<'lua> { /// Creates an empty `MultiValue` containing no values. From eed277cd9875b537c8754476968e5a919e7338cd Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 13:44:18 +0100 Subject: [PATCH 06/18] Update documentation for FromLuaMulti. Signed-off-by: Tin --- src/value.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/value.rs b/src/value.rs index 840129d7..513a8ea6 100644 --- a/src/value.rs +++ b/src/value.rs @@ -187,6 +187,15 @@ pub trait FromLuaMulti<'lua>: Sized { /// values should be ignored. This reflects the semantics of Lua when calling a function or /// assigning values. Similarly, if not enough values are given, conversions should assume that /// any missing values are nil. + /// + /// The `consumed` reference should be updated accordingly to notify the outer scope + /// about the number of values that were used to perform the conversion. Failing to + /// do so will make the outer scope try and use the same sequence of `values` for + /// multiple consecutive conversions. + /// In case of an error, the `consumed` counter value should be kept the same to allow + /// wrappers such as [`Variadic`] to conservatively capture values. + /// + /// [`Variadic`]: struct.Variadic.html fn from_lua_multi( values: MultiValue<'lua>, lua: Context<'lua>, From ec0f177b25ed82a3388682ecd2a08f3ccbe27f41 Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 14:10:54 +0100 Subject: [PATCH 07/18] Fix Vec loop Make Variadic loop more explicit Signed-off-by: Tin --- src/conversion.rs | 2 +- src/multi.rs | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/conversion.rs b/src/conversion.rs index c6a1eeb1..85066a0a 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -451,8 +451,8 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLua<'lua> for Vec { .collect(), ); let mut result = Vec::new(); - let mut consumed = 0; while values.len() > 0 { + let mut consumed = 0; match T::from_lua_multi(values.clone(), lua, &mut consumed) { Ok(it) => { result.push(it); diff --git a/src/multi.rs b/src/multi.rs index 2011eab3..0abb3177 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -154,13 +154,16 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { lua: Context<'lua>, total: &mut usize, ) -> Result { - let mut consumed = 0; let mut result = Vec::new(); - while let Ok(it) = T::from_lua_multi(values.clone(), lua, &mut consumed) { - result.push(it); - values.drop_front(consumed); - *total += consumed; - consumed = 0; + while values.len() > 0 { + let mut consumed = 0; + if let Ok(it) = T::from_lua_multi(values.clone(), lua, &mut consumed) { + result.push(it); + values.drop_front(consumed); + *total += consumed; + } else { + break; + } } Ok(Variadic(result)) } From a160aa9a094023068d14f9dd1dd39ff1989162e5 Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 14:23:07 +0100 Subject: [PATCH 08/18] Fix vector element insertion order Signed-off-by: Tin --- src/conversion.rs | 2 +- src/value.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/conversion.rs b/src/conversion.rs index 85066a0a..8953206f 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -444,7 +444,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Vec { impl<'lua, T: FromLuaMulti<'lua>> FromLua<'lua> for Vec { fn from_lua(value: Value<'lua>, lua: Context<'lua>) -> Result { if let Value::Table(table) = value { - let mut values: MultiValue = MultiValue( + let mut values: MultiValue = MultiValue::from_vec( table .sequence_values::() .filter_map(Result::ok) // Every value in Table is always a Value diff --git a/src/value.rs b/src/value.rs index 513a8ea6..4cd45812 100644 --- a/src/value.rs +++ b/src/value.rs @@ -83,7 +83,7 @@ pub trait FromLua<'lua>: Sized { /// Multiple Lua values used for both argument passing and also for multiple return values. #[derive(Debug, Clone)] -pub struct MultiValue<'lua>(pub(crate) Vec>); +pub struct MultiValue<'lua>(Vec>); impl<'lua> MultiValue<'lua> { /// Creates an empty `MultiValue` containing no values. @@ -143,7 +143,7 @@ impl<'lua> MultiValue<'lua> { } pub(crate) fn push_front_many(&mut self, values: Self) { - self.0.extend(values.into_iter()); + self.0.extend(values.0.into_iter()); } pub(crate) fn pop_front(&mut self) -> Option> { From 68edf35cdf5442c57fd7bec343c54d77b2472031 Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 14:43:19 +0100 Subject: [PATCH 09/18] Add test for MultiValue append Signed-off-by: Tin --- src/multi.rs | 4 ++-- src/value.rs | 2 +- tests/tests.rs | 39 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/multi.rs b/src/multi.rs index 0abb3177..da71e9c2 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -228,11 +228,11 @@ macro_rules! impl_tuple { macro_rules! push_reverse { ($multi_value:expr, $first:expr, $($rest:expr,)*) => ( push_reverse!($multi_value, $($rest,)*); - $multi_value.push_front_many($first); + $multi_value.append($first); ); ($multi_value:expr, $first:expr) => ( - $multi_value.push_front_many($first); + $multi_value.append($first); ); ($multi_value:expr,) => (); diff --git a/src/value.rs b/src/value.rs index 4cd45812..cbd6b5be 100644 --- a/src/value.rs +++ b/src/value.rs @@ -142,7 +142,7 @@ impl<'lua> MultiValue<'lua> { self.0.push(value); } - pub(crate) fn push_front_many(&mut self, values: Self) { + pub(crate) fn append(&mut self, values: Self) { self.0.extend(values.0.into_iter()); } diff --git a/tests/tests.rs b/tests/tests.rs index 2ef3c8e9..9fbf936e 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -5,8 +5,8 @@ use std::sync::Arc; use std::{error, f32, f64, fmt}; use rlua::{ - Error, ExternalError, Function, InitFlags, Lua, Nil, Result, StdLib, String, Table, UserData, - Value, Variadic, + Error, ExternalError, Function, InitFlags, Lua, MultiValue, Nil, Result, StdLib, String, Table, + ToLua, ToLuaMulti, UserData, Value, Variadic, }; #[test] @@ -137,6 +137,41 @@ fn test_lua_multi() { }); } +#[test] +fn test_lua_multi_concat() { + Lua::new().context(|lua| { + let globals = lua.globals(); + lua.load( + r#" + function pass_through(arg1, arg2, arg3, arg4) + return arg1, arg2, arg3, arg4 + end + "#, + ) + .exec() + .unwrap(); + + struct Point(u64, u64); + + impl<'lua> ToLuaMulti<'lua> for Point { + fn to_lua_multi( + self, + lua: rlua::prelude::LuaContext<'lua>, + ) -> Result> { + Ok(MultiValue::from_iter( + [self.0, self.1].map(|it| it.to_lua(lua).unwrap()), + )) + } + } + + let pass_through = globals.get::<_, Function>("pass_through").unwrap(); + let (a, b, c, d) = pass_through + .call::<_, (u64, u64, u64, u64)>((Point(1, 2), Point(3, 4))) + .unwrap(); + assert_eq!((a, b, c, d), (1, 2, 3, 4)); + }); +} + #[test] fn test_coercion() { Lua::new().context(|lua| { From e8f419065aca0b805119c4c64320217eefd73fa0 Mon Sep 17 00:00:00 2001 From: Tin Date: Mon, 20 Nov 2023 14:57:31 +0100 Subject: [PATCH 10/18] Make drop_front saturating_sub provided count This prevents a panic when count is bigger than length Signed-off-by: Tin --- src/value.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/value.rs b/src/value.rs index cbd6b5be..3e839267 100644 --- a/src/value.rs +++ b/src/value.rs @@ -151,7 +151,7 @@ impl<'lua> MultiValue<'lua> { } pub(crate) fn drop_front(&mut self, count: usize) { - self.0.drain(self.0.len() - count..).count(); + self.0.drain(self.0.len().saturating_sub(count)..).count(); } pub fn len(&self) -> usize { From f3cc089f793726fc4a74a1ee2adc3567fdba3d9f Mon Sep 17 00:00:00 2001 From: Tin Date: Tue, 21 Nov 2023 00:38:53 +0100 Subject: [PATCH 11/18] Simplify impl_tuple. Idea from: https://github.com/kyren/piccolo/commit/24a2c1683c1ec879fd2e90985a6307a7aa3401e3 Signed-off-by: Tin --- src/multi.rs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/multi.rs b/src/multi.rs index da71e9c2..97b4ae26 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -170,24 +170,11 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { } macro_rules! impl_tuple { - () => ( - impl<'lua> ToLuaMulti<'lua> for () { - fn to_lua_multi(self, _: Context<'lua>) -> Result> { - Ok(MultiValue::new()) - } - } - - impl<'lua> FromLuaMulti<'lua> for () { - fn from_lua_multi(_: MultiValue, _: Context<'lua>, _: &mut usize) -> Result { - Ok(()) - } - } - ); - - ($($name:ident)+) => ( + ($($name:ident)*) => ( impl<'lua, $($name),*> ToLuaMulti<'lua> for ($($name,)*) where $($name: ToLuaMulti<'lua>),* { + #[allow(unused_variables)] #[allow(unused_mut)] #[allow(non_snake_case)] fn to_lua_multi(self, lua: Context<'lua>) -> Result> { @@ -202,6 +189,7 @@ macro_rules! impl_tuple { impl<'lua, $($name),*> FromLuaMulti<'lua> for ($($name,)*) where $($name: FromLuaMulti<'lua>),* { + #[allow(unused_variables)] #[allow(unused_mut)] #[allow(non_snake_case)] fn from_lua_multi(mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize) -> Result { From 928131be6eaf1db13719cb38fbf0012beef02187 Mon Sep 17 00:00:00 2001 From: Tin Date: Thu, 7 Dec 2023 06:42:58 +0100 Subject: [PATCH 12/18] Implement fixes from alternative implementation Signed-off-by: Tin --- src/context.rs | 15 +++----- src/conversion.rs | 6 +++- src/function.rs | 3 +- src/multi.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++++ src/scope.rs | 27 +++++---------- src/thread.rs | 3 +- src/value.rs | 4 +++ 7 files changed, 113 insertions(+), 33 deletions(-) diff --git a/src/context.rs b/src/context.rs index d8cb5648..74ebecbb 100644 --- a/src/context.rs +++ b/src/context.rs @@ -179,8 +179,7 @@ impl<'lua> Context<'lua> { F: 'static + Send + Fn(Context<'lua>, A) -> Result, { self.create_callback(Box::new(move |lua, args| { - let mut consumed = 0; - func(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + func(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })) } @@ -1136,8 +1135,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { if let Some(front) = args.pop_front() { let userdata = AnyUserData::from_lua(front, lua)?; let userdata = userdata.borrow::()?; - let mut consumed = 0; - method(lua, &userdata, A::from_lua_multi(args, lua, &mut consumed)?)? + method(lua, &userdata, A::from_lua_multi(args, lua, &mut 0)?)? .to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { @@ -1163,11 +1161,10 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let mut method = method .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - let mut consumed = 0; (&mut *method)( lua, &mut userdata, - A::from_lua_multi(args, lua, &mut consumed)?, + A::from_lua_multi(args, lua, &mut 0)?, )? .to_lua_multi(lua) } else { @@ -1187,8 +1184,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { F: 'static + Send + Fn(Context<'lua>, A) -> Result, { Box::new(move |lua, args| { - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) }) } @@ -1203,8 +1199,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let function = &mut *function .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) }) } } diff --git a/src/conversion.rs b/src/conversion.rs index 8953206f..cd9b84ec 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -531,9 +531,13 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Option { lua: Context<'lua>, consumed: &mut usize, ) -> Result { + let front = values.peek_front(); + if front.is_none() || front.map(|it| matches!(it, Nil)).unwrap_or_default() { + return Ok(None); + } match T::from_lua_multi(values, lua, consumed) { Ok(it) => Ok(Some(it)), - Err(_) => Ok(None), + Err(err) => Err(err), } } } diff --git a/src/function.rs b/src/function.rs index fd745880..1dc01bcb 100644 --- a/src/function.rs +++ b/src/function.rs @@ -88,8 +88,7 @@ impl<'lua> Function<'lua> { ffi::lua_pop(lua.state, 1); results }; - let mut consumed = 0; - R::from_lua_multi(results, lua, &mut consumed) + R::from_lua_multi(results, lua, &mut 0) } /// Returns a function that, when called, calls `self`, passing `args` as the first set of diff --git a/src/multi.rs b/src/multi.rs index 97b4ae26..ae5cce4d 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -169,6 +169,94 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { } } +/// Wrapper for arguments that allowed to fail during conversion. +/// +/// Note that failing includes recieving a `nil` value if the type isn't +/// convertible from `nil`. That is, this wrapper allows _skipping_ arguments in +/// called functions. Capturing nil for skippable arguments can be done through +/// `Fallible>` as it will have a value of `Some(None)` when +/// converting from `nil`. +/// +/// In case where `nil` argument is expected (must be specified from the +/// script), `Option` should be used instead of `Fallible`. +/// +/// If conversion is successful, the value will be `Some(T)`. +/// +/// Conversely, if conversion fails, the value will be `None`, and `consumed` +/// argument counter will stay unchanged. +pub struct Fallible(Option); + +impl Fallible { + /// Returns inner `Option`. + pub fn into_option(self) -> Option { + self.0 + } + + /// Maps fallible type using provided `mapping` function into another + /// `Option`. + pub fn map R>(self, mapping: F) -> Option { + self.0.map(mapping) + } + + /// Unwraps fallible type or panics if conversion failed. + pub fn unwrap(self) -> T { + self.0.unwrap() + } + /// Unwraps fallible type or returns `value` if conversion failed. + pub fn unwrap_or(self, value: T) -> T { + self.0.unwrap_or(value) + } + /// Unwraps fallible type or returns a return value of `init` if conversion + /// failed. + pub fn unwrap_or_else T>(self, f: F) -> T { + self.0.unwrap_or_else(f) + } + /// Unwraps fallible type or returns the default value if conversion failed. + pub fn unwrap_or_default(self) -> T + where + T: Default, + { + self.0.unwrap_or_else(T::default) + } + /// Retuns `other` `Option` if this argument conversion failed. + pub fn or(self, other: Option) -> Option { + self.0.or(other) + } + /// Retuns `Option` value returned by `f` if this argument conversion + /// failed. + pub fn or_else Option>(self, f: F) -> Option { + self.0.or_else(f) + } +} + +impl Deref for Fallible { + type Target = Option; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl DerefMut for Fallible { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Fallible { + fn from_lua_multi( + values: MultiValue<'lua>, + lua: Context<'lua>, + consumed: &mut usize, + ) -> Result { + match T::from_lua_multi(values, lua, consumed) { + Ok(it) => { + *consumed += 1; + Ok(Fallible(Some(it))) + } + Err(_) => Ok(Fallible(None)), + } + } +} + macro_rules! impl_tuple { ($($name:ident)*) => ( impl<'lua, $($name),*> ToLuaMulti<'lua> for ($($name,)*) diff --git a/src/scope.rs b/src/scope.rs index 048bab0b..9876ac0b 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -64,8 +64,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> { // scope, and owned inside the callback itself. unsafe { self.create_callback(Box::new(move |lua, args| { - let mut consumed = 0; - func(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + func(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })) } } @@ -382,8 +381,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Method(Box::new(move |lua, ud, args| { - let mut consumed = 0; - method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -398,8 +396,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - let mut consumed = 0; - method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -414,8 +411,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Function(Box::new(move |lua, args| { - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -430,8 +426,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -445,8 +440,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Method(Box::new(move |lua, ud, args| { - let mut consumed = 0; - method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -460,8 +454,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - let mut consumed = 0; - method(lua, ud, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -475,8 +468,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Function(Box::new(move |lua, args| { - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } @@ -490,8 +482,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - let mut consumed = 0; - function(lua, A::from_lua_multi(args, lua, &mut consumed)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) })), )); } diff --git a/src/thread.rs b/src/thread.rs index 2464ad0e..96c02e06 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -119,8 +119,7 @@ impl<'lua> Thread<'lua> { } results }; - let mut consumed = 0; - R::from_lua_multi(results, lua, &mut consumed) + R::from_lua_multi(results, lua, &mut 0) } /// Gets the status of the thread. diff --git a/src/value.rs b/src/value.rs index 3e839267..517f8088 100644 --- a/src/value.rs +++ b/src/value.rs @@ -150,6 +150,10 @@ impl<'lua> MultiValue<'lua> { self.0.pop() } + pub(crate) fn peek_front(&self) -> Option<&Value<'lua>> { + self.0.last() + } + pub(crate) fn drop_front(&mut self, count: usize) { self.0.drain(self.0.len().saturating_sub(count)..).count(); } From ba5b7d37ea07bfafd20e8223b52f2e0d4697e5f4 Mon Sep 17 00:00:00 2001 From: Tin Date: Thu, 7 Dec 2023 06:55:16 +0100 Subject: [PATCH 13/18] Implement as separate method Signed-off-by: Tin --- src/context.rs | 20 ++++++-------------- src/conversion.rs | 6 +++--- src/function.rs | 2 +- src/lib.rs | 2 +- src/multi.rs | 16 ++++++++-------- src/prelude.rs | 14 +++++++------- src/scope.rs | 18 +++++++++--------- src/thread.rs | 2 +- src/value.rs | 46 ++++++++++++++++++++++++++++++++-------------- 9 files changed, 68 insertions(+), 58 deletions(-) diff --git a/src/context.rs b/src/context.rs index 74ebecbb..238d7249 100644 --- a/src/context.rs +++ b/src/context.rs @@ -179,7 +179,7 @@ impl<'lua> Context<'lua> { F: 'static + Send + Fn(Context<'lua>, A) -> Result, { self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })) } @@ -370,7 +370,7 @@ impl<'lua> Context<'lua> { value: MultiValue<'lua>, consumed: &mut usize, ) -> Result { - T::from_lua_multi(value, self, consumed) + T::from_counted_multi(value, self, consumed) } /// Set a value in the Lua registry based on a string name. @@ -1135,8 +1135,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { if let Some(front) = args.pop_front() { let userdata = AnyUserData::from_lua(front, lua)?; let userdata = userdata.borrow::()?; - method(lua, &userdata, A::from_lua_multi(args, lua, &mut 0)?)? - .to_lua_multi(lua) + method(lua, &userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1161,12 +1160,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let mut method = method .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - (&mut *method)( - lua, - &mut userdata, - A::from_lua_multi(args, lua, &mut 0)?, - )? - .to_lua_multi(lua) + (&mut *method)(lua, &mut userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1183,9 +1177,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { R: ToLuaMulti<'lua>, F: 'static + Send + Fn(Context<'lua>, A) -> Result, { - Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) - }) + Box::new(move |lua, args| function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua)) } fn box_function_mut(function: F) -> Callback<'lua, 'static> @@ -1199,7 +1191,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let function = &mut *function .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) }) } } diff --git a/src/conversion.rs b/src/conversion.rs index cd9b84ec..1b78aad3 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -453,7 +453,7 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLua<'lua> for Vec { let mut result = Vec::new(); while values.len() > 0 { let mut consumed = 0; - match T::from_lua_multi(values.clone(), lua, &mut consumed) { + match T::from_counted_multi(values.clone(), lua, &mut consumed) { Ok(it) => { result.push(it); values.drop_front(consumed); @@ -526,7 +526,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Option { - fn from_lua_multi( + fn from_counted_multi( values: crate::MultiValue<'lua>, lua: Context<'lua>, consumed: &mut usize, @@ -535,7 +535,7 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Option { if front.is_none() || front.map(|it| matches!(it, Nil)).unwrap_or_default() { return Ok(None); } - match T::from_lua_multi(values, lua, consumed) { + match T::from_counted_multi(values, lua, consumed) { Ok(it) => Ok(Some(it)), Err(err) => Err(err), } diff --git a/src/function.rs b/src/function.rs index 1dc01bcb..cb98b756 100644 --- a/src/function.rs +++ b/src/function.rs @@ -88,7 +88,7 @@ impl<'lua> Function<'lua> { ffi::lua_pop(lua.state, 1); results }; - R::from_lua_multi(results, lua, &mut 0) + R::from_lua_multi(results, lua) } /// Returns a function that, when called, calls `self`, passing `args` as the first set of diff --git a/src/lib.rs b/src/lib.rs index 37e8cc7c..724a60ae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,7 +71,7 @@ pub use crate::error::{Error, ExternalError, ExternalResult, Result}; pub use crate::function::Function; pub use crate::hook::{Debug, DebugNames, DebugSource, DebugStack, HookTriggers}; pub use crate::lua::{InitFlags, Lua, StdLib}; -pub use crate::multi::Variadic; +pub use crate::multi::{Variadic, Fallible}; pub use crate::scope::Scope; pub use crate::string::String; pub use crate::table::{Table, TablePairs, TableSequence}; diff --git a/src/multi.rs b/src/multi.rs index ae5cce4d..eef04775 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -33,7 +33,7 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T { } impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T { - fn from_lua_multi( + fn from_counted_multi( mut values: MultiValue<'lua>, lua: Context<'lua>, consumed: &mut usize, @@ -55,7 +55,7 @@ impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { } impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { - fn from_lua_multi( + fn from_counted_multi( values: MultiValue<'lua>, _: Context<'lua>, consumed: &mut usize, @@ -149,7 +149,7 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { - fn from_lua_multi( + fn from_counted_multi( mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize, @@ -157,7 +157,7 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { let mut result = Vec::new(); while values.len() > 0 { let mut consumed = 0; - if let Ok(it) = T::from_lua_multi(values.clone(), lua, &mut consumed) { + if let Ok(it) = T::from_counted_multi(values.clone(), lua, &mut consumed) { result.push(it); values.drop_front(consumed); *total += consumed; @@ -242,12 +242,12 @@ impl DerefMut for Fallible { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Fallible { - fn from_lua_multi( + fn from_counted_multi( values: MultiValue<'lua>, lua: Context<'lua>, consumed: &mut usize, ) -> Result { - match T::from_lua_multi(values, lua, consumed) { + match T::from_counted_multi(values, lua, consumed) { Ok(it) => { *consumed += 1; Ok(Fallible(Some(it))) @@ -280,11 +280,11 @@ macro_rules! impl_tuple { #[allow(unused_variables)] #[allow(unused_mut)] #[allow(non_snake_case)] - fn from_lua_multi(mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize) -> Result { + fn from_counted_multi(mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize) -> Result { $( let $name = { let mut consumed = 0; - let it = match FromLuaMulti::from_lua_multi(values.clone(), lua, &mut consumed) { + let it = match FromLuaMulti::from_counted_multi(values.clone(), lua, &mut consumed) { Ok(it) => it, Err(err) => { return Err(err); diff --git a/src/prelude.rs b/src/prelude.rs index f55b87a0..242a1d1c 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -4,11 +4,11 @@ pub use crate::{ AnyUserData as LuaAnyUserData, Chunk as LuaChunk, Context as LuaContext, Debug as LuaDebug, DebugNames as LuaDebugNames, DebugSource as LuaDebugSource, DebugStack as LuaDebugStack, Error as LuaError, ExternalError as LuaExternalError, ExternalResult as LuaExternalResult, - FromLua, FromLuaMulti, Function as LuaFunction, HookTriggers as LuaHookTriggers, - Integer as LuaInteger, LightUserData as LuaLightUserData, Lua, MetaMethod as LuaMetaMethod, - MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber, RegistryKey as LuaRegistryKey, - Result as LuaResult, Scope as LuaScope, String as LuaString, Table as LuaTable, - TablePairs as LuaTablePairs, TableSequence as LuaTableSequence, Thread as LuaThread, - ThreadStatus as LuaThreadStatus, ToLua, ToLuaMulti, UserData as LuaUserData, - UserDataMethods as LuaUserDataMethods, Value as LuaValue, + Fallible as LuaFallible, FromLua, FromLuaMulti, Function as LuaFunction, + HookTriggers as LuaHookTriggers, Integer as LuaInteger, LightUserData as LuaLightUserData, Lua, + MetaMethod as LuaMetaMethod, MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber, + RegistryKey as LuaRegistryKey, Result as LuaResult, Scope as LuaScope, String as LuaString, + Table as LuaTable, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence, + Thread as LuaThread, ThreadStatus as LuaThreadStatus, ToLua, ToLuaMulti, + UserData as LuaUserData, UserDataMethods as LuaUserDataMethods, Value as LuaValue, }; diff --git a/src/scope.rs b/src/scope.rs index 9876ac0b..d6f16df1 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -64,7 +64,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> { // scope, and owned inside the callback itself. unsafe { self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })) } } @@ -381,7 +381,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -396,7 +396,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -411,7 +411,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -426,7 +426,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.methods.push(( name.as_ref().to_vec(), NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -440,7 +440,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -454,7 +454,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -468,7 +468,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } @@ -482,7 +482,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l self.meta_methods.push(( meta, NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua, &mut 0)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) })), )); } diff --git a/src/thread.rs b/src/thread.rs index 96c02e06..0bd9a012 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -119,7 +119,7 @@ impl<'lua> Thread<'lua> { } results }; - R::from_lua_multi(results, lua, &mut 0) + R::from_lua_multi(results, lua) } /// Gets the status of the thread. diff --git a/src/value.rs b/src/value.rs index 517f8088..2bdf65c0 100644 --- a/src/value.rs +++ b/src/value.rs @@ -182,27 +182,45 @@ pub trait ToLuaMulti<'lua> { /// Trait for types that can be created from an arbitrary number of Lua values. /// -/// This is a generalization of `FromLua`, allowing an arbitrary number of Lua values to participate -/// in the conversion. Any type that implements `FromLua` will automatically implement this trait. +/// This is a generalization of `FromLua`, allowing an arbitrary number of Lua +/// values to participate in the conversion. Any type that implements `FromLua` +/// will automatically implement this trait. +/// +/// Implementing either `from_lua_multi` or `from_counted_multi` is required as +/// the default implementations recursively call each other. pub trait FromLuaMulti<'lua>: Sized { /// Performs the conversion. /// - /// In case `values` contains more values than needed to perform the conversion, the excess - /// values should be ignored. This reflects the semantics of Lua when calling a function or - /// assigning values. Similarly, if not enough values are given, conversions should assume that - /// any missing values are nil. + /// In case `values` contains more values than needed to perform the + /// conversion, the excess values should be ignored. This reflects the + /// semantics of Lua when calling a function or assigning values. Similarly, + /// if not enough values are given, conversions should assume that any + /// missing values are nil. + fn from_lua_multi(values: MultiValue<'lua>, lua: Context<'lua>) -> Result { + Self::from_lua_multi(values, lua) + } + + /// Same as `from_lua_multi`, additionally allowing specification of number + /// of arguments that were consumed by incrementing the `consumed` + /// reference. + /// + /// This allows the outer scope to know the number of values that were used + /// to perform the conversion. /// - /// The `consumed` reference should be updated accordingly to notify the outer scope - /// about the number of values that were used to perform the conversion. Failing to - /// do so will make the outer scope try and use the same sequence of `values` for - /// multiple consecutive conversions. - /// In case of an error, the `consumed` counter value should be kept the same to allow - /// wrappers such as [`Variadic`] to conservatively capture values. + /// Failing to do so will make the outer scope try and use the same sequence + /// of `values` for multiple consecutive conversions. In case of an error, + /// the `consumed` counter value should be kept the same to allow wrappers + /// such as [`Variadic`] to conservatively capture values. /// /// [`Variadic`]: struct.Variadic.html - fn from_lua_multi( + fn from_counted_multi( values: MultiValue<'lua>, lua: Context<'lua>, consumed: &mut usize, - ) -> Result; + ) -> Result { + let count = values.len(); + let result = Self::from_lua_multi(values, lua); + *consumed += count; + result + } } From d4dc15a1fb2c953d2320072db54d33397524d10d Mon Sep 17 00:00:00 2001 From: Tin Date: Thu, 7 Dec 2023 06:58:22 +0100 Subject: [PATCH 14/18] Revert unpack_multi Signed-off-by: Tin --- src/context.rs | 8 ++------ src/value.rs | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/context.rs b/src/context.rs index 238d7249..5f5ff0f0 100644 --- a/src/context.rs +++ b/src/context.rs @@ -365,12 +365,8 @@ impl<'lua> Context<'lua> { } /// Converts a `MultiValue` instance into a value that implements `FromLuaMulti`. - pub fn unpack_multi>( - self, - value: MultiValue<'lua>, - consumed: &mut usize, - ) -> Result { - T::from_counted_multi(value, self, consumed) + pub fn unpack_multi>(self, value: MultiValue<'lua>) -> Result { + T::from_lua_multi(value, self) } /// Set a value in the Lua registry based on a string name. diff --git a/src/value.rs b/src/value.rs index 2bdf65c0..36fda5ca 100644 --- a/src/value.rs +++ b/src/value.rs @@ -197,7 +197,7 @@ pub trait FromLuaMulti<'lua>: Sized { /// if not enough values are given, conversions should assume that any /// missing values are nil. fn from_lua_multi(values: MultiValue<'lua>, lua: Context<'lua>) -> Result { - Self::from_lua_multi(values, lua) + Self::from_counted_multi(values, lua, &mut 0) } /// Same as `from_lua_multi`, additionally allowing specification of number From fc47ac90840faca2ec5b28fc82092440bc26c56d Mon Sep 17 00:00:00 2001 From: Tin Date: Thu, 7 Dec 2023 07:09:24 +0100 Subject: [PATCH 15/18] Run format Signed-off-by: Tin --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 724a60ae..8b18ac4c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,7 +71,7 @@ pub use crate::error::{Error, ExternalError, ExternalResult, Result}; pub use crate::function::Function; pub use crate::hook::{Debug, DebugNames, DebugSource, DebugStack, HookTriggers}; pub use crate::lua::{InitFlags, Lua, StdLib}; -pub use crate::multi::{Variadic, Fallible}; +pub use crate::multi::{Fallible, Variadic}; pub use crate::scope::Scope; pub use crate::string::String; pub use crate::table::{Table, TablePairs, TableSequence}; From 0332b6ccf8aeae399199a5ccb3a6fcff2e595e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20=C5=A0vagelj?= Date: Sun, 24 Dec 2023 09:47:48 +0100 Subject: [PATCH 16/18] Use &mut MultiValue in to_lua_multi MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tin Švagelj --- src/context.rs | 21 ++++++++------- src/conversion.rs | 12 +++------ src/function.rs | 4 +-- src/multi.rs | 66 +++++++++++++---------------------------------- src/scope.rs | 36 +++++++++++++------------- src/thread.rs | 4 +-- src/value.rs | 56 ++++++++++++---------------------------- 7 files changed, 72 insertions(+), 127 deletions(-) diff --git a/src/context.rs b/src/context.rs index 5f5ff0f0..be9e46e1 100644 --- a/src/context.rs +++ b/src/context.rs @@ -178,8 +178,8 @@ impl<'lua> Context<'lua> { R: ToLuaMulti<'lua>, F: 'static + Send + Fn(Context<'lua>, A) -> Result, { - self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + self.create_callback(Box::new(move |lua, mut args| { + func(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })) } @@ -365,8 +365,8 @@ impl<'lua> Context<'lua> { } /// Converts a `MultiValue` instance into a value that implements `FromLuaMulti`. - pub fn unpack_multi>(self, value: MultiValue<'lua>) -> Result { - T::from_lua_multi(value, self) + pub fn unpack_multi>(self, mut value: MultiValue<'lua>) -> Result { + T::from_lua_multi(&mut value, self) } /// Set a value in the Lua registry based on a string name. @@ -1131,7 +1131,7 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { if let Some(front) = args.pop_front() { let userdata = AnyUserData::from_lua(front, lua)?; let userdata = userdata.borrow::()?; - method(lua, &userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + method(lua, &userdata, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1156,7 +1156,8 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { let mut method = method .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - (&mut *method)(lua, &mut userdata, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + (&mut *method)(lua, &mut userdata, A::from_lua_multi(&mut args, lua)?)? + .to_lua_multi(lua) } else { Err(Error::FromLuaConversionError { from: "missing argument", @@ -1173,7 +1174,9 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { R: ToLuaMulti<'lua>, F: 'static + Send + Fn(Context<'lua>, A) -> Result, { - Box::new(move |lua, args| function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua)) + Box::new(move |lua, mut args| { + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) + }) } fn box_function_mut(function: F) -> Callback<'lua, 'static> @@ -1183,11 +1186,11 @@ impl<'lua, T: 'static + UserData> StaticUserDataMethods<'lua, T> { F: 'static + Send + FnMut(Context<'lua>, A) -> Result, { let function = RefCell::new(function); - Box::new(move |lua, args| { + Box::new(move |lua, mut args| { let function = &mut *function .try_borrow_mut() .map_err(|_| Error::RecursiveMutCallback)?; - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) }) } } diff --git a/src/conversion.rs b/src/conversion.rs index 1b78aad3..b99b5933 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -452,11 +452,9 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLua<'lua> for Vec { ); let mut result = Vec::new(); while values.len() > 0 { - let mut consumed = 0; - match T::from_counted_multi(values.clone(), lua, &mut consumed) { + match T::from_lua_multi(&mut values, lua) { Ok(it) => { result.push(it); - values.drop_front(consumed); } Err(err) => return Err(err), } @@ -526,16 +524,12 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Option { - fn from_counted_multi( - values: crate::MultiValue<'lua>, - lua: Context<'lua>, - consumed: &mut usize, - ) -> Result { + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { let front = values.peek_front(); if front.is_none() || front.map(|it| matches!(it, Nil)).unwrap_or_default() { return Ok(None); } - match T::from_counted_multi(values, lua, consumed) { + match T::from_lua_multi(values, lua) { Ok(it) => Ok(Some(it)), Err(err) => Err(err), } diff --git a/src/function.rs b/src/function.rs index cb98b756..36398be0 100644 --- a/src/function.rs +++ b/src/function.rs @@ -65,7 +65,7 @@ impl<'lua> Function<'lua> { let args = args.to_lua_multi(lua)?; let nargs = args.len() as c_int; - let results = unsafe { + let mut results = unsafe { let _sg = StackGuard::new(lua.state); check_stack(lua.state, nargs + 3)?; @@ -88,7 +88,7 @@ impl<'lua> Function<'lua> { ffi::lua_pop(lua.state, 1); results }; - R::from_lua_multi(results, lua) + R::from_lua_multi(&mut results, lua) } /// Returns a function that, when called, calls `self`, passing `args` as the first set of diff --git a/src/multi.rs b/src/multi.rs index eef04775..6816bb9d 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -33,16 +33,9 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T { } impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T { - fn from_counted_multi( - mut values: MultiValue<'lua>, - lua: Context<'lua>, - consumed: &mut usize, - ) -> Result { + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { match values.pop_front() { - Some(it) => { - *consumed += 1; - Ok(T::from_lua(it, lua)?) - } + Some(it) => Ok(T::from_lua(it, lua)?), None => Ok(T::from_lua(Nil, lua)?), } } @@ -55,13 +48,10 @@ impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { } impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { - fn from_counted_multi( - values: MultiValue<'lua>, - _: Context<'lua>, - consumed: &mut usize, - ) -> Result { - *consumed += values.len(); - Ok(values) + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + let mut result = MultiValue::new(); + result.append(values); + Ok(result) } } @@ -149,18 +139,11 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { - fn from_counted_multi( - mut values: MultiValue<'lua>, - lua: Context<'lua>, - total: &mut usize, - ) -> Result { + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { let mut result = Vec::new(); while values.len() > 0 { - let mut consumed = 0; - if let Ok(it) = T::from_counted_multi(values.clone(), lua, &mut consumed) { + if let Ok(it) = T::from_lua_multi(values, lua) { result.push(it); - values.drop_front(consumed); - *total += consumed; } else { break; } @@ -242,16 +225,9 @@ impl DerefMut for Fallible { } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Fallible { - fn from_counted_multi( - values: MultiValue<'lua>, - lua: Context<'lua>, - consumed: &mut usize, - ) -> Result { - match T::from_counted_multi(values, lua, consumed) { - Ok(it) => { - *consumed += 1; - Ok(Fallible(Some(it))) - } + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + match T::from_lua_multi(values, lua) { + Ok(it) => Ok(Fallible(Some(it))), Err(_) => Ok(Fallible(None)), } } @@ -269,7 +245,7 @@ macro_rules! impl_tuple { let ($($name,)*) = self; let mut results = MultiValue::new(); - push_reverse!(results, $($name.to_lua_multi(lua)?,)*); + push_reverse!(results, $(&mut $name.to_lua_multi(lua)?,)*); Ok(results) } } @@ -280,19 +256,13 @@ macro_rules! impl_tuple { #[allow(unused_variables)] #[allow(unused_mut)] #[allow(non_snake_case)] - fn from_counted_multi(mut values: MultiValue<'lua>, lua: Context<'lua>, total: &mut usize) -> Result { + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { $( - let $name = { - let mut consumed = 0; - let it = match FromLuaMulti::from_counted_multi(values.clone(), lua, &mut consumed) { - Ok(it) => it, - Err(err) => { - return Err(err); - } - }; - *total += consumed; - values.drop_front(consumed); - it + let $name = match FromLuaMulti::from_lua_multi(values, lua) { + Ok(it) => it, + Err(err) => { + return Err(err); + } }; )* Ok(($($name,)*)) diff --git a/src/scope.rs b/src/scope.rs index d6f16df1..9406f66f 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -63,8 +63,8 @@ impl<'lua, 'scope> Scope<'lua, 'scope> { // to make sure callbacks can't capture handles with lifetime outside the scope, inside the // scope, and owned inside the callback itself. unsafe { - self.create_callback(Box::new(move |lua, args| { - func(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + self.create_callback(Box::new(move |lua, mut args| { + func(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })) } } @@ -380,8 +380,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.methods.push(( name.as_ref().to_vec(), - NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::Method(Box::new(move |lua, ud, mut args| { + method(lua, ud, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -395,8 +395,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.methods.push(( name.as_ref().to_vec(), - NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::MethodMut(Box::new(move |lua, ud, mut args| { + method(lua, ud, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -410,8 +410,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.methods.push(( name.as_ref().to_vec(), - NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::Function(Box::new(move |lua, mut args| { + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -425,8 +425,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.methods.push(( name.as_ref().to_vec(), - NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::FunctionMut(Box::new(move |lua, mut args| { + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -439,8 +439,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.meta_methods.push(( meta, - NonStaticMethod::Method(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::Method(Box::new(move |lua, ud, mut args| { + method(lua, ud, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -453,8 +453,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.meta_methods.push(( meta, - NonStaticMethod::MethodMut(Box::new(move |lua, ud, args| { - method(lua, ud, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::MethodMut(Box::new(move |lua, ud, mut args| { + method(lua, ud, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -467,8 +467,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.meta_methods.push(( meta, - NonStaticMethod::Function(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::Function(Box::new(move |lua, mut args| { + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } @@ -481,8 +481,8 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> for NonStaticUserDataMethods<'l { self.meta_methods.push(( meta, - NonStaticMethod::FunctionMut(Box::new(move |lua, args| { - function(lua, A::from_lua_multi(args, lua)?)?.to_lua_multi(lua) + NonStaticMethod::FunctionMut(Box::new(move |lua, mut args| { + function(lua, A::from_lua_multi(&mut args, lua)?)?.to_lua_multi(lua) })), )); } diff --git a/src/thread.rs b/src/thread.rs index 0bd9a012..bd69c023 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -77,7 +77,7 @@ impl<'lua> Thread<'lua> { { let lua = self.0.lua; let args = args.to_lua_multi(lua)?; - let results = unsafe { + let mut results = unsafe { let _sg = StackGuard::new(lua.state); assert_stack(lua.state, 3); @@ -119,7 +119,7 @@ impl<'lua> Thread<'lua> { } results }; - R::from_lua_multi(results, lua) + R::from_lua_multi(&mut results, lua) } /// Gets the status of the thread. diff --git a/src/value.rs b/src/value.rs index 36fda5ca..b5ac1236 100644 --- a/src/value.rs +++ b/src/value.rs @@ -138,24 +138,28 @@ impl<'lua> MultiValue<'lua> { self.0.reserve(size); } - pub(crate) fn push_front(&mut self, value: Value<'lua>) { + pub fn push_front(&mut self, value: Value<'lua>) { self.0.push(value); } - pub(crate) fn append(&mut self, values: Self) { - self.0.extend(values.0.into_iter()); + pub(crate) fn append(&mut self, values: &mut Self) { + self.0.append(&mut values.0); } - pub(crate) fn pop_front(&mut self) -> Option> { + pub fn pop_front(&mut self) -> Option> { self.0.pop() } - pub(crate) fn peek_front(&self) -> Option<&Value<'lua>> { + pub fn pop_front_n(&mut self, count: usize) -> impl Iterator> + '_ { + self.0.drain((self.0.len() - count)..).rev() + } + + pub fn peek_front(&self) -> Option<&Value<'lua>> { self.0.last() } - pub(crate) fn drop_front(&mut self, count: usize) { - self.0.drain(self.0.len().saturating_sub(count)..).count(); + pub fn peek_front_n(&self, count: usize) -> impl Iterator> + '_ { + self.0.iter().rev().take(count) } pub fn len(&self) -> usize { @@ -191,36 +195,10 @@ pub trait ToLuaMulti<'lua> { pub trait FromLuaMulti<'lua>: Sized { /// Performs the conversion. /// - /// In case `values` contains more values than needed to perform the - /// conversion, the excess values should be ignored. This reflects the - /// semantics of Lua when calling a function or assigning values. Similarly, - /// if not enough values are given, conversions should assume that any - /// missing values are nil. - fn from_lua_multi(values: MultiValue<'lua>, lua: Context<'lua>) -> Result { - Self::from_counted_multi(values, lua, &mut 0) - } - - /// Same as `from_lua_multi`, additionally allowing specification of number - /// of arguments that were consumed by incrementing the `consumed` - /// reference. - /// - /// This allows the outer scope to know the number of values that were used - /// to perform the conversion. - /// - /// Failing to do so will make the outer scope try and use the same sequence - /// of `values` for multiple consecutive conversions. In case of an error, - /// the `consumed` counter value should be kept the same to allow wrappers - /// such as [`Variadic`] to conservatively capture values. - /// - /// [`Variadic`]: struct.Variadic.html - fn from_counted_multi( - values: MultiValue<'lua>, - lua: Context<'lua>, - consumed: &mut usize, - ) -> Result { - let count = values.len(); - let result = Self::from_lua_multi(values, lua); - *consumed += count; - result - } + /// Implementation should pop needed `values` and leave the rest intact. In + /// case a value wasn't needed for the conversion, it should be pushed back + /// so the latter conversions can use it. If not enough values are given, + /// conversions should assume that any missing values are nil to reflect Lua + /// semantics. + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result; } From ffb0feb7c7d3c0655dbf3a2fc898dd90d5157ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20=C5=A0vagelj?= Date: Thu, 28 Dec 2023 23:58:15 +0100 Subject: [PATCH 17/18] Cleanup comment and unused variable name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tin Švagelj --- src/multi.rs | 2 +- src/value.rs | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/multi.rs b/src/multi.rs index 6816bb9d..ffc1e5e5 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -48,7 +48,7 @@ impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { } impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { - fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + fn from_lua_multi(values: &mut MultiValue<'lua>, _: Context<'lua>) -> Result { let mut result = MultiValue::new(); result.append(values); Ok(result) diff --git a/src/value.rs b/src/value.rs index b5ac1236..07ccb141 100644 --- a/src/value.rs +++ b/src/value.rs @@ -189,16 +189,13 @@ pub trait ToLuaMulti<'lua> { /// This is a generalization of `FromLua`, allowing an arbitrary number of Lua /// values to participate in the conversion. Any type that implements `FromLua` /// will automatically implement this trait. -/// -/// Implementing either `from_lua_multi` or `from_counted_multi` is required as -/// the default implementations recursively call each other. pub trait FromLuaMulti<'lua>: Sized { /// Performs the conversion. /// /// Implementation should pop needed `values` and leave the rest intact. In /// case a value wasn't needed for the conversion, it should be pushed back /// so the latter conversions can use it. If not enough values are given, - /// conversions should assume that any missing values are nil to reflect Lua - /// semantics. + /// implementation should assume that any missing values are nil to reflect + /// Lua semantics. fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result; } From 6ad86b57f66902fa964b00d4a1f0907aeff4bf70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20=C5=A0vagelj?= Date: Tue, 6 Feb 2024 04:31:03 +0100 Subject: [PATCH 18/18] Make it more convenient to push values into MultiValue MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tin Švagelj --- src/value.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 3 deletions(-) diff --git a/src/value.rs b/src/value.rs index 07ccb141..9d90f9bd 100644 --- a/src/value.rs +++ b/src/value.rs @@ -69,6 +69,58 @@ impl<'lua> Value<'lua> { } } +impl<'lua> From for Value<'lua> { + fn from(value: bool) -> Self { + Value::Boolean(value) + } +} +impl<'lua> From for Value<'lua> { + fn from(value: LightUserData) -> Self { + Value::LightUserData(value) + } +} +#[cfg(any(rlua_lua53, rlua_lua54))] +impl<'lua> From for Value<'lua> { + fn from(value: Integer) -> Self { + Value::Integer(value) + } +} +impl<'lua> From for Value<'lua> { + fn from(value: Number) -> Self { + Value::Number(value) + } +} +impl<'lua> From> for Value<'lua> { + fn from(value: String<'lua>) -> Self { + Value::String(value) + } +} +impl<'lua> From> for Value<'lua> { + fn from(value: Table<'lua>) -> Self { + Value::Table(value) + } +} +impl<'lua> From> for Value<'lua> { + fn from(value: Function<'lua>) -> Self { + Value::Function(value) + } +} +impl<'lua> From> for Value<'lua> { + fn from(value: Thread<'lua>) -> Self { + Value::Thread(value) + } +} +impl<'lua> From> for Value<'lua> { + fn from(value: AnyUserData<'lua>) -> Self { + Value::UserData(value) + } +} +impl<'lua> From for Value<'lua> { + fn from(value: Error) -> Self { + Value::Error(value) + } +} + /// Trait for types convertible to `Value`. pub trait ToLua<'lua> { /// Performs the conversion. @@ -118,7 +170,7 @@ impl<'a, 'lua> IntoIterator for &'a MultiValue<'lua> { type IntoIter = iter::Rev>>; fn into_iter(self) -> Self::IntoIter { - (&self.0).into_iter().rev() + self.0.iter().rev() } } @@ -138,8 +190,8 @@ impl<'lua> MultiValue<'lua> { self.0.reserve(size); } - pub fn push_front(&mut self, value: Value<'lua>) { - self.0.push(value); + pub fn push_front(&mut self, value: impl Into>) { + self.0.push(value.into()); } pub(crate) fn append(&mut self, values: &mut Self) {