diff --git a/src/context.rs b/src/context.rs index 5f5ff0f..be9e46e 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 966c08e..b99b593 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, MultiValue}; impl<'lua> ToLua<'lua> for Value<'lua> { fn to_lua(self, _: Context<'lua>) -> Result> { @@ -440,10 +441,25 @@ 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::from_vec( + table + .sequence_values::() + .filter_map(Result::ok) // Every value in Table is always a Value + .collect(), + ); + let mut result = Vec::new(); + while values.len() > 0 { + match T::from_lua_multi(&mut values, lua) { + Ok(it) => { + result.push(it); + } + Err(err) => return Err(err), + } + } + Ok(result) } else { Err(Error::FromLuaConversionError { from: value.type_name(), @@ -507,11 +523,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: &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_lua_multi(values, lua) { + Ok(it) => Ok(Some(it)), + Err(err) => Err(err), } } } diff --git a/src/function.rs b/src/function.rs index cb98b75..36398be 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/lib.rs b/src/lib.rs index 37e8cc7..8b18ac4 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::{Fallible, Variadic}; 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 9a050b0..ffc1e5e 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -33,8 +33,11 @@ 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(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + match values.pop_front() { + Some(it) => Ok(T::from_lua(it, lua)?), + None => Ok(T::from_lua(Nil, lua)?), + } } } @@ -45,8 +48,10 @@ impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { } impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { - fn from_lua_multi(values: MultiValue<'lua>, _: Context<'lua>) -> Result { - Ok(values) + fn from_lua_multi(values: &mut MultiValue<'lua>, _: Context<'lua>) -> Result { + let mut result = MultiValue::new(); + result.append(values); + Ok(result) } } @@ -85,6 +90,11 @@ impl Variadic { pub fn new() -> Variadic { Variadic(Vec::new()) } + + #[inline] + pub fn len(&self) -> usize { + self.0.len() + } } impl Default for Variadic { @@ -128,57 +138,134 @@ 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 - .into_iter() - .map(|e| T::from_lua(e, lua)) - .collect::>>() - .map(Variadic) +impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for Variadic { + fn from_lua_multi(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + let mut result = Vec::new(); + while values.len() > 0 { + if let Ok(it) = T::from_lua_multi(values, lua) { + result.push(it); + } else { + break; + } + } + Ok(Variadic(result)) } } -macro_rules! impl_tuple { - () => ( - impl<'lua> ToLuaMulti<'lua> for () { - fn to_lua_multi(self, _: Context<'lua>) -> Result> { - Ok(MultiValue::new()) - } - } +/// 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<'lua> FromLuaMulti<'lua> for () { - fn from_lua_multi(_: MultiValue, _: Context<'lua>) -> Result { - Ok(()) - } +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: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + match T::from_lua_multi(values, lua) { + Ok(it) => Ok(Fallible(Some(it))), + Err(_) => Ok(Fallible(None)), } - ); + } +} - ($last:ident $($name:ident)*) => ( - impl<'lua, $($name,)* $last> ToLuaMulti<'lua> for ($($name,)* $last,) - where $($name: ToLua<'lua>,)* - $last: ToLuaMulti<'lua> +macro_rules! impl_tuple { + ($($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> { - 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, $(&mut $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_variables)] #[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(values: &mut MultiValue<'lua>, lua: Context<'lua>) -> Result { + $( + let $name = match FromLuaMulti::from_lua_multi(values, lua) { + Ok(it) => it, + Err(err) => { + return Err(err); + } + }; + )* + Ok(($($name,)*)) } } ); @@ -187,11 +274,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.append($first); ); ($multi_value:expr, $first:expr) => ( - $multi_value.push_front($first); + $multi_value.append($first); ); ($multi_value:expr,) => (); diff --git a/src/prelude.rs b/src/prelude.rs index f55b87a..242a1d1 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 d6f16df..9406f66 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 0bd9a01..bd69c02 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 3c9862f..9d90f9b 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,14 +190,30 @@ impl<'lua> MultiValue<'lua> { self.0.reserve(size); } - pub(crate) 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 pop_front(&mut self) -> Option> { + pub(crate) fn append(&mut self, values: &mut Self) { + self.0.append(&mut values.0); + } + + pub fn pop_front(&mut self) -> Option> { self.0.pop() } + 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 fn peek_front_n(&self, count: usize) -> impl Iterator> + '_ { + self.0.iter().rev().take(count) + } + pub fn len(&self) -> usize { self.0.len() } @@ -170,14 +238,16 @@ 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. 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; + /// 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, + /// 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; } diff --git a/tests/tests.rs b/tests/tests.rs index 2ef3c8e..9fbf936 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| {