Skip to main content

luaur_rt/
conversion.rs

1//! `FromLua` / `IntoLua` / `FromLuaMulti` / `IntoLuaMulti` impls for the common
2//! Rust types. Mirrors the impls in `mlua::conversion`.
3
4use crate::error::{Error, Result};
5use crate::function::Function;
6use crate::multi::{MultiValue, Variadic};
7use crate::state::Lua;
8use crate::string::LuaString;
9use crate::sys::{lua_tonumberx, lua_type, ttype};
10use crate::table::Table;
11use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
12use crate::value::{Integer, Number, Value};
13use core::ffi::c_int;
14
15// ---------------------------------------------------------------------------
16// Value itself
17// ---------------------------------------------------------------------------
18
19impl IntoLua for Value {
20    fn into_lua(self, _lua: &Lua) -> Result<Value> {
21        Ok(self)
22    }
23}
24
25impl FromLua for Value {
26    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
27        Ok(value)
28    }
29}
30
31// ---------------------------------------------------------------------------
32// Unit / nil
33// ---------------------------------------------------------------------------
34//
35// NOTE: `()` is deliberately NOT a single-value (`IntoLua`/`FromLua`) type.
36// In Lua, `()` means *zero* values, not one nil — so it implements only the
37// multi-value traits below (producing/consuming no stack values). This also
38// avoids a coherence clash with the blanket `impl<T: IntoLua> IntoLuaMulti`.
39
40// `()` as a *multi* value means "no values" in both directions.
41impl IntoLuaMulti for () {
42    fn into_lua_multi(self, _lua: &Lua) -> Result<MultiValue> {
43        Ok(MultiValue::new())
44    }
45}
46
47impl FromLuaMulti for () {
48    fn from_lua_multi(_values: MultiValue, _lua: &Lua) -> Result<Self> {
49        Ok(())
50    }
51}
52
53// ---------------------------------------------------------------------------
54// bool
55// ---------------------------------------------------------------------------
56
57impl IntoLua for bool {
58    fn into_lua(self, _lua: &Lua) -> Result<Value> {
59        Ok(Value::Boolean(self))
60    }
61}
62
63impl FromLua for bool {
64    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
65        // Lua truthiness: nil and false are false, everything else is true.
66        Ok(match value {
67            Value::Nil => false,
68            Value::Boolean(b) => b,
69            _ => true,
70        })
71    }
72}
73
74// ---------------------------------------------------------------------------
75// Integers (range-checked)
76// ---------------------------------------------------------------------------
77
78macro_rules! impl_integer {
79    ($($ty:ty),*) => {$(
80        impl IntoLua for $ty {
81            fn into_lua(self, _lua: &Lua) -> Result<Value> {
82                let as_i64 = i64::try_from(self).map_err(|_| Error::ToLuaConversionError {
83                    from: stringify!($ty),
84                    to: "integer",
85                    message: Some("value out of i64 range".to_string()),
86                })?;
87                Ok(Value::Integer(as_i64))
88            }
89        }
90
91        impl FromLua for $ty {
92            fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
93                // Convert an (already truncated, finite) float directly into the
94                // target type with a range check against its f64 bounds, so a
95                // value beyond `i64` range (e.g. `2^64` for `u64`) is correctly
96                // rejected rather than silently saturating through `i64`.
97                fn from_float(f: f64) -> Result<$ty> {
98                    // Truncate toward zero, then range-check in `i128` space so a
99                    // value beyond the target's range (e.g. `2^64` for `u64`) is
100                    // rejected rather than saturating. Values whose magnitude
101                    // exceeds `i128` are likewise out of range for any `$ty`.
102                    let t = f.trunc();
103                    if t < (i128::MIN as f64) || t > (i128::MAX as f64) {
104                        return Err(Error::FromLuaConversionError {
105                            from: "number",
106                            to: stringify!($ty).to_string(),
107                            message: Some("out of range".to_string()),
108                        });
109                    }
110                    let wide = t as i128;
111                    <$ty>::try_from(wide).map_err(|_| Error::FromLuaConversionError {
112                        from: "number",
113                        to: stringify!($ty).to_string(),
114                        message: Some("out of range".to_string()),
115                    })
116                }
117                match value {
118                    Value::Integer(i) => {
119                        <$ty>::try_from(i).map_err(|_| Error::FromLuaConversionError {
120                            from: "number",
121                            to: stringify!($ty).to_string(),
122                            message: Some("out of range".to_string()),
123                        })
124                    }
125                    Value::Number(f) => {
126                        // Luau is f64-backed: `tonumber`/`lua_tointegerx`
127                        // **truncate** a fractional float toward zero rather than
128                        // rejecting it (matching mlua on the Luau backend). A
129                        // non-finite number has no integer representation.
130                        if !f.is_finite() {
131                            return Err(Error::FromLuaConversionError {
132                                from: "number",
133                                to: stringify!($ty).to_string(),
134                                message: Some("number has no integer representation".to_string()),
135                            });
136                        }
137                        from_float(f)
138                    }
139                    // Lua coerces numeric strings to numbers (mirrors mlua's
140                    // string fallback for integer conversions).
141                    Value::String(ref s) => {
142                        let text = s.to_string_lossy();
143                        let trimmed = text.trim();
144                        if let Ok(i) = trimmed.parse::<i64>() {
145                            <$ty>::try_from(i).map_err(|_| Error::FromLuaConversionError {
146                                from: "string",
147                                to: stringify!($ty).to_string(),
148                                message: Some("out of range".to_string()),
149                            })
150                        } else if let Ok(f) = trimmed.parse::<f64>() {
151                            if !f.is_finite() {
152                                return Err(Error::FromLuaConversionError {
153                                    from: "string",
154                                    to: stringify!($ty).to_string(),
155                                    message: Some("number has no integer representation".to_string()),
156                                });
157                            }
158                            from_float(f)
159                        } else {
160                            Err(Error::FromLuaConversionError {
161                                from: "string",
162                                to: stringify!($ty).to_string(),
163                                message: Some("not a number".to_string()),
164                            })
165                        }
166                    }
167                    other => {
168                        Err(Error::FromLuaConversionError {
169                            from: other.type_name(),
170                            to: stringify!($ty).to_string(),
171                            message: None,
172                        })
173                    }
174                }
175            }
176        }
177    )*};
178}
179
180impl_integer!(i8, u8, i16, u16, i32, u32, i64, u64, isize, usize);
181
182// 128-bit integers exceed Luau's f64-backed number range, so they round-trip
183// **lossily** through `f64` (matching mlua, which has no 128-bit Lua number).
184// Values within f64's exactly-representable range survive the round trip.
185macro_rules! impl_integer_128 {
186    ($($ty:ty),*) => {$(
187        impl IntoLua for $ty {
188            fn into_lua(self, _lua: &Lua) -> Result<Value> {
189                Ok(Value::Number(self as f64))
190            }
191        }
192
193        impl FromLua for $ty {
194            fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
195                let n: f64 = match value {
196                    Value::Integer(i) => i as f64,
197                    Value::Number(f) => f,
198                    Value::String(ref s) => {
199                        s.to_string_lossy().trim().parse::<f64>().map_err(|_| {
200                            Error::FromLuaConversionError {
201                                from: "string",
202                                to: stringify!($ty).to_string(),
203                                message: Some("not a number".to_string()),
204                            }
205                        })?
206                    }
207                    other => {
208                        return Err(Error::FromLuaConversionError {
209                            from: other.type_name(),
210                            to: stringify!($ty).to_string(),
211                            message: None,
212                        });
213                    }
214                };
215                if n.fract() != 0.0 || !n.is_finite() {
216                    return Err(Error::FromLuaConversionError {
217                        from: "number",
218                        to: stringify!($ty).to_string(),
219                        message: Some("number has no integer representation".to_string()),
220                    });
221                }
222                Ok(n as $ty)
223            }
224        }
225    )*};
226}
227
228impl_integer_128!(i128, u128);
229
230// `Integer` is `i64`, already covered by impl_integer.
231const _: () = {
232    // Compile-time assertion that Integer == i64.
233    fn _assert(_x: Integer) -> i64 {
234        _x
235    }
236};
237
238// ---------------------------------------------------------------------------
239// Floats
240// ---------------------------------------------------------------------------
241
242impl IntoLua for f64 {
243    fn into_lua(self, _lua: &Lua) -> Result<Value> {
244        Ok(Value::Number(self))
245    }
246}
247
248impl IntoLua for f32 {
249    fn into_lua(self, _lua: &Lua) -> Result<Value> {
250        Ok(Value::Number(self as Number))
251    }
252}
253
254// The `from_stack` overrides below are the stack fast path mirroring mlua's
255// `lua_convert_float!`: they read the raw `lua_Number` straight off the stack,
256// bypassing the `Value` representation, which preserves details `Value` folds
257// away (notably the sign bit of `-0.0`, which `value_from_stack`'s
258// whole-number normalization to `Value::Integer` would drop). The value-level
259// `from_lua` behavior is unchanged.
260impl FromLua for f64 {
261    unsafe fn from_stack(idx: c_int, lua: &Lua) -> Result<Self> {
262        let state = lua.state();
263        unsafe {
264            if lua_type(state, idx) == ttype::NUMBER {
265                // `lua_tonumberx` with a null `isnum` out-param: the
266                // conversion cannot fail for an actual number.
267                return Ok(lua_tonumberx(state, idx, core::ptr::null_mut()));
268            }
269        }
270        // Fall back to the value-level conversion (string coercion and error
271        // messages stay identical to the slow path).
272        Self::from_lua(lua.value_from_stack(idx)?, lua)
273    }
274
275    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
276        match value {
277            Value::Number(n) => Ok(n),
278            Value::Integer(i) => Ok(i as f64),
279            // Lua coerces numeric strings to numbers (mirrors mlua).
280            Value::String(ref s) => {
281                let text = s.to_string_lossy();
282                text.trim()
283                    .parse::<f64>()
284                    .map_err(|_| Error::FromLuaConversionError {
285                        from: "string",
286                        to: "f64".to_string(),
287                        message: Some("not a number".to_string()),
288                    })
289            }
290            other => Err(Error::FromLuaConversionError {
291                from: other.type_name(),
292                to: "f64".to_string(),
293                message: None,
294            }),
295        }
296    }
297}
298
299impl FromLua for f32 {
300    unsafe fn from_stack(idx: c_int, lua: &Lua) -> Result<Self> {
301        let state = lua.state();
302        unsafe {
303            if lua_type(state, idx) == ttype::NUMBER {
304                return Ok(lua_tonumberx(state, idx, core::ptr::null_mut()) as f32);
305            }
306        }
307        Self::from_lua(lua.value_from_stack(idx)?, lua)
308    }
309
310    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
311        Ok(f64::from_lua(value, lua)? as f32)
312    }
313}
314
315// ---------------------------------------------------------------------------
316// Strings
317// ---------------------------------------------------------------------------
318
319impl IntoLua for String {
320    fn into_lua(self, lua: &Lua) -> Result<Value> {
321        Ok(Value::String(lua.create_string(&self)))
322    }
323}
324
325impl IntoLua for &str {
326    fn into_lua(self, lua: &Lua) -> Result<Value> {
327        Ok(Value::String(lua.create_string(self)))
328    }
329}
330
331impl IntoLua for &String {
332    fn into_lua(self, lua: &Lua) -> Result<Value> {
333        Ok(Value::String(lua.create_string(self)))
334    }
335}
336
337impl FromLua for String {
338    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
339        match value {
340            Value::String(s) => s.to_str(),
341            // Lua coerces numbers to strings in many contexts; mirror that.
342            Value::Integer(i) => Ok(i.to_string()),
343            Value::Number(n) => Ok(n.to_string()),
344            other => Err(Error::FromLuaConversionError {
345                from: other.type_name(),
346                to: "String".to_string(),
347                message: None,
348            }),
349        }
350    }
351}
352
353impl IntoLua for LuaString {
354    fn into_lua(self, _lua: &Lua) -> Result<Value> {
355        Ok(Value::String(self))
356    }
357}
358
359impl IntoLua for &LuaString {
360    fn into_lua(self, _lua: &Lua) -> Result<Value> {
361        Ok(Value::String(self.clone()))
362    }
363}
364
365impl FromLua for LuaString {
366    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
367        match value {
368            Value::String(s) => Ok(s),
369            Value::Integer(i) => Ok(_lua.create_string(i.to_string())),
370            Value::Number(n) => Ok(_lua.create_string(n.to_string())),
371            other => Err(Error::FromLuaConversionError {
372                from: other.type_name(),
373                to: "String".to_string(),
374                message: None,
375            }),
376        }
377    }
378}
379
380// ---------------------------------------------------------------------------
381// Handles (Table, Function)
382// ---------------------------------------------------------------------------
383
384impl IntoLua for Table {
385    fn into_lua(self, _lua: &Lua) -> Result<Value> {
386        Ok(Value::Table(self))
387    }
388}
389
390impl IntoLua for &Table {
391    fn into_lua(self, _lua: &Lua) -> Result<Value> {
392        Ok(Value::Table(self.clone()))
393    }
394}
395
396impl FromLua for Table {
397    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
398        match value {
399            Value::Table(t) => Ok(t),
400            other => Err(Error::FromLuaConversionError {
401                from: other.type_name(),
402                to: "Table".to_string(),
403                message: None,
404            }),
405        }
406    }
407}
408
409impl IntoLua for Function {
410    fn into_lua(self, _lua: &Lua) -> Result<Value> {
411        Ok(Value::Function(self))
412    }
413}
414
415impl IntoLua for &Function {
416    fn into_lua(self, _lua: &Lua) -> Result<Value> {
417        Ok(Value::Function(self.clone()))
418    }
419}
420
421impl FromLua for Function {
422    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
423        match value {
424            Value::Function(f) => Ok(f),
425            other => Err(Error::FromLuaConversionError {
426                from: other.type_name(),
427                to: "Function".to_string(),
428                message: None,
429            }),
430        }
431    }
432}
433
434// ---------------------------------------------------------------------------
435// Vector (Luau) <-> Value::Vector
436// ---------------------------------------------------------------------------
437
438impl IntoLua for crate::Vector {
439    fn into_lua(self, _lua: &Lua) -> Result<Value> {
440        Ok(Value::Vector(self))
441    }
442}
443
444impl FromLua for crate::Vector {
445    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
446        match value {
447            Value::Vector(v) => Ok(v),
448            other => Err(Error::FromLuaConversionError {
449                from: other.type_name(),
450                to: "vector".to_string(),
451                message: None,
452            }),
453        }
454    }
455}
456
457// ---------------------------------------------------------------------------
458// Buffer (Luau) <-> Value::Buffer
459// ---------------------------------------------------------------------------
460
461impl IntoLua for crate::Buffer {
462    fn into_lua(self, _lua: &Lua) -> Result<Value> {
463        Ok(Value::Buffer(self))
464    }
465}
466
467impl IntoLua for &crate::Buffer {
468    fn into_lua(self, _lua: &Lua) -> Result<Value> {
469        Ok(Value::Buffer(self.clone()))
470    }
471}
472
473impl FromLua for crate::Buffer {
474    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
475        match value {
476            Value::Buffer(buf) => Ok(buf),
477            other => Err(Error::FromLuaConversionError {
478                from: other.type_name(),
479                to: "buffer".to_string(),
480                message: None,
481            }),
482        }
483    }
484}
485
486// ---------------------------------------------------------------------------
487// Option<T>
488// ---------------------------------------------------------------------------
489
490impl<T: IntoLua> IntoLua for Option<T> {
491    fn into_lua(self, lua: &Lua) -> Result<Value> {
492        match self {
493            Some(v) => v.into_lua(lua),
494            None => Ok(Value::Nil),
495        }
496    }
497}
498
499impl<T: FromLua> FromLua for Option<T> {
500    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
501        match value {
502            Value::Nil => Ok(None),
503            other => Ok(Some(T::from_lua(other, lua)?)),
504        }
505    }
506}
507
508// ---------------------------------------------------------------------------
509// Vec<T> <-> sequence table
510// ---------------------------------------------------------------------------
511
512impl<T: IntoLua> IntoLua for Vec<T> {
513    fn into_lua(self, lua: &Lua) -> Result<Value> {
514        let table = lua.create_table();
515        for (i, item) in self.into_iter().enumerate() {
516            // Lua sequences are 1-based.
517            table.set((i + 1) as i64, item)?;
518        }
519        Ok(Value::Table(table))
520    }
521}
522
523impl<T: IntoLua + Clone> IntoLua for &[T] {
524    fn into_lua(self, lua: &Lua) -> Result<Value> {
525        let table = lua.create_table();
526        for (i, item) in self.iter().enumerate() {
527            table.raw_set((i + 1) as i64, item.clone())?;
528        }
529        Ok(Value::Table(table))
530    }
531}
532
533impl<T: FromLua> FromLua for Vec<T> {
534    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
535        match value {
536            Value::Table(t) => {
537                let len = t.raw_len();
538                let mut out = Vec::with_capacity(len);
539                for i in 1..=len {
540                    out.push(t.raw_get::<T>(i as i64)?);
541                }
542                Ok(out)
543            }
544            other => Err(Error::FromLuaConversionError {
545                from: other.type_name(),
546                to: "Vec".to_string(),
547                message: None,
548            }),
549        }
550    }
551}
552
553// ---------------------------------------------------------------------------
554// Fixed-size arrays [T; N] <-> sequence table
555// ---------------------------------------------------------------------------
556
557impl<T: IntoLua, const N: usize> IntoLua for [T; N] {
558    fn into_lua(self, lua: &Lua) -> Result<Value> {
559        let table = lua.create_table();
560        for (i, item) in self.into_iter().enumerate() {
561            table.raw_set((i + 1) as i64, item)?;
562        }
563        Ok(Value::Table(table))
564    }
565}
566
567impl<T: FromLua, const N: usize> FromLua for [T; N] {
568    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
569        // A Luau vector converts to an array of its components (matching mlua:
570        // `let v: [f64; 3] = lua.load("vector.create(1,2,3)").eval()?`).
571        if let Value::Vector(v) = value {
572            if N == crate::Vector::SIZE {
573                let x = T::from_lua(Value::Number(v.x() as f64), lua)?;
574                let y = T::from_lua(Value::Number(v.y() as f64), lua)?;
575                let z = T::from_lua(Value::Number(v.z() as f64), lua)?;
576                let comps = vec![x, y, z];
577                return <[T; N]>::try_from(comps).map_err(|_| Error::FromLuaConversionError {
578                    from: "vector",
579                    to: format!("[T; {N}]"),
580                    message: None,
581                });
582            }
583            return Err(Error::FromLuaConversionError {
584                from: "vector",
585                to: format!("[T; {N}]"),
586                message: Some(format!(
587                    "expected array of length {}, got {N}",
588                    crate::Vector::SIZE
589                )),
590            });
591        }
592        let vec: Vec<T> = Vec::from_lua(value, lua)?;
593        let len = vec.len();
594        <[T; N]>::try_from(vec).map_err(|_| Error::FromLuaConversionError {
595            from: "table",
596            to: format!("[T; {N}]"),
597            message: Some(format!("expected table of length {N}, got {len}")),
598        })
599    }
600}
601
602// ---------------------------------------------------------------------------
603// HashMap / BTreeMap <-> table
604// ---------------------------------------------------------------------------
605
606use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
607use std::hash::Hash;
608
609impl<K: IntoLua + Eq + Hash, V: IntoLua, S: std::hash::BuildHasher> IntoLua for HashMap<K, V, S> {
610    fn into_lua(self, lua: &Lua) -> Result<Value> {
611        let table = lua.create_table();
612        for (k, v) in self {
613            table.raw_set(k, v)?;
614        }
615        Ok(Value::Table(table))
616    }
617}
618
619impl<K: FromLua + Eq + Hash, V: FromLua, S: std::hash::BuildHasher + Default> FromLua
620    for HashMap<K, V, S>
621{
622    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
623        match value {
624            Value::Table(t) => {
625                let mut out = HashMap::with_hasher(S::default());
626                for pair in t.pairs::<K, V>() {
627                    let (k, v) = pair?;
628                    out.insert(k, v);
629                }
630                Ok(out)
631            }
632            other => Err(Error::FromLuaConversionError {
633                from: other.type_name(),
634                to: "HashMap".to_string(),
635                message: None,
636            }),
637        }
638    }
639}
640
641impl<K: IntoLua + Ord, V: IntoLua> IntoLua for BTreeMap<K, V> {
642    fn into_lua(self, lua: &Lua) -> Result<Value> {
643        let table = lua.create_table();
644        for (k, v) in self {
645            table.raw_set(k, v)?;
646        }
647        Ok(Value::Table(table))
648    }
649}
650
651impl<K: FromLua + Ord, V: FromLua> FromLua for BTreeMap<K, V> {
652    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
653        match value {
654            Value::Table(t) => {
655                let mut out = BTreeMap::new();
656                for pair in t.pairs::<K, V>() {
657                    let (k, v) = pair?;
658                    out.insert(k, v);
659                }
660                Ok(out)
661            }
662            other => Err(Error::FromLuaConversionError {
663                from: other.type_name(),
664                to: "BTreeMap".to_string(),
665                message: None,
666            }),
667        }
668    }
669}
670
671// ---------------------------------------------------------------------------
672// HashSet / BTreeSet <-> table (values become keys mapped to `true`)
673// ---------------------------------------------------------------------------
674
675impl<T: IntoLua + Eq + Hash, S: std::hash::BuildHasher> IntoLua for HashSet<T, S> {
676    fn into_lua(self, lua: &Lua) -> Result<Value> {
677        let table = lua.create_table();
678        for item in self {
679            table.raw_set(item, true)?;
680        }
681        Ok(Value::Table(table))
682    }
683}
684
685impl<T: FromLua + Eq + Hash, S: std::hash::BuildHasher + Default> FromLua for HashSet<T, S> {
686    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
687        from_lua_set(value, lua, "HashSet", |it| {
688            let mut out = HashSet::with_hasher(S::default());
689            for v in it {
690                out.insert(v?);
691            }
692            Ok(out)
693        })
694    }
695}
696
697impl<T: IntoLua + Ord> IntoLua for BTreeSet<T> {
698    fn into_lua(self, lua: &Lua) -> Result<Value> {
699        let table = lua.create_table();
700        for item in self {
701            table.raw_set(item, true)?;
702        }
703        Ok(Value::Table(table))
704    }
705}
706
707impl<T: FromLua + Ord> FromLua for BTreeSet<T> {
708    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
709        from_lua_set(value, lua, "BTreeSet", |it| {
710            let mut out = BTreeSet::new();
711            for v in it {
712                out.insert(v?);
713            }
714            Ok(out)
715        })
716    }
717}
718
719/// A Lua table can represent a set in two ways (matching mlua): as a sequence
720/// of values `{a, b, c}`, or as a map of keys `{[a] = true, ...}`. We support
721/// both: if the table has a non-empty sequence part, take its values;
722/// otherwise take its keys.
723fn from_lua_set<T: FromLua, C>(
724    value: Value,
725    _lua: &Lua,
726    to: &'static str,
727    build: impl FnOnce(SetIter<T>) -> Result<C>,
728) -> Result<C> {
729    match value {
730        Value::Table(t) => {
731            if t.raw_len() > 0 {
732                build(SetIter::Seq(t.sequence_values::<T>()))
733            } else {
734                let keys: Vec<Result<T>> =
735                    t.pairs::<T, Value>().map(|p| p.map(|(k, _)| k)).collect();
736                build(SetIter::Keys(keys.into_iter()))
737            }
738        }
739        other => Err(Error::FromLuaConversionError {
740            from: other.type_name(),
741            to: to.to_string(),
742            message: None,
743        }),
744    }
745}
746
747enum SetIter<T: FromLua> {
748    Seq(crate::table::TableSequence<T>),
749    Keys(std::vec::IntoIter<Result<T>>),
750}
751
752impl<T: FromLua> Iterator for SetIter<T> {
753    type Item = Result<T>;
754    fn next(&mut self) -> Option<Self::Item> {
755        match self {
756            SetIter::Seq(s) => s.next(),
757            SetIter::Keys(k) => k.next(),
758        }
759    }
760}
761
762// ---------------------------------------------------------------------------
763// char
764// ---------------------------------------------------------------------------
765
766impl IntoLua for char {
767    fn into_lua(self, lua: &Lua) -> Result<Value> {
768        Ok(Value::String(lua.create_string(self.to_string())))
769    }
770}
771
772impl FromLua for char {
773    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
774        match value {
775            Value::String(_) | Value::Integer(_) | Value::Number(_) => {}
776            other => {
777                return Err(Error::FromLuaConversionError {
778                    from: other.type_name(),
779                    to: "char".to_string(),
780                    message: Some("expected string or integer".to_string()),
781                })
782            }
783        }
784        if let Value::Integer(_) | Value::Number(_) = value {
785            let i = i64::from_lua(value, lua)?;
786            let cp = u32::try_from(i).ok().and_then(char::from_u32);
787            return cp.ok_or(Error::FromLuaConversionError {
788                from: "number",
789                to: "char".to_string(),
790                message: Some("integer out of range for a unicode char".to_string()),
791            });
792        }
793        let s = String::from_lua(value, lua)?;
794        let mut chars = s.chars();
795        match (chars.next(), chars.next()) {
796            (Some(c), None) => Ok(c),
797            _ => Err(Error::FromLuaConversionError {
798                from: "string",
799                to: "char".to_string(),
800                message: Some("expected string to have exactly one char".to_string()),
801            }),
802        }
803    }
804}
805
806// ---------------------------------------------------------------------------
807// Cow<str>, Box<str>, CString
808// ---------------------------------------------------------------------------
809
810impl IntoLua for std::borrow::Cow<'_, str> {
811    fn into_lua(self, lua: &Lua) -> Result<Value> {
812        Ok(Value::String(lua.create_string(self.as_ref())))
813    }
814}
815
816impl IntoLua for Box<str> {
817    fn into_lua(self, lua: &Lua) -> Result<Value> {
818        Ok(Value::String(lua.create_string(&*self)))
819    }
820}
821
822impl FromLua for Box<str> {
823    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
824        Ok(String::from_lua(value, lua)?.into_boxed_str())
825    }
826}
827
828impl IntoLua for std::ffi::CString {
829    fn into_lua(self, lua: &Lua) -> Result<Value> {
830        Ok(Value::String(lua.create_string(self.as_bytes())))
831    }
832}
833
834impl FromLua for std::ffi::CString {
835    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
836        let bytes = match value {
837            Value::String(s) => s.as_bytes(),
838            other => {
839                return Err(Error::FromLuaConversionError {
840                    from: other.type_name(),
841                    to: "CString".to_string(),
842                    message: None,
843                })
844            }
845        };
846        std::ffi::CString::new(bytes).map_err(|e| Error::FromLuaConversionError {
847            from: "string",
848            to: "CString".to_string(),
849            message: Some(format!("interior nul byte: {e}")),
850        })
851    }
852}
853
854impl<T: IntoLua> IntoLua for Box<[T]> {
855    fn into_lua(self, lua: &Lua) -> Result<Value> {
856        self.into_vec().into_lua(lua)
857    }
858}
859
860impl<T: FromLua> FromLua for Box<[T]> {
861    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
862        Ok(Vec::<T>::from_lua(value, lua)?.into_boxed_slice())
863    }
864}
865
866// ---------------------------------------------------------------------------
867// Variadic<T>
868// ---------------------------------------------------------------------------
869
870impl<T: IntoLua> IntoLuaMulti for Variadic<T> {
871    fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
872        let vec: Vec<T> = self.into();
873        let mut m = MultiValue::with_capacity(vec.len());
874        for item in vec {
875            m.push_back(item.into_lua(lua)?);
876        }
877        Ok(m)
878    }
879}
880
881impl<T: FromLua> FromLuaMulti for Variadic<T> {
882    fn from_lua_multi(values: MultiValue, lua: &Lua) -> Result<Self> {
883        let mut out = Vec::with_capacity(values.len());
884        for v in values {
885            out.push(T::from_lua(v, lua)?);
886        }
887        Ok(Variadic::from(out))
888    }
889}
890
891// ---------------------------------------------------------------------------
892// Error <-> Value::Error  +  Result<T, E> : IntoLuaMulti
893// ---------------------------------------------------------------------------
894
895impl IntoLua for crate::light_userdata::LightUserData {
896    fn into_lua(self, _lua: &Lua) -> Result<Value> {
897        Ok(Value::LightUserData(self))
898    }
899}
900
901impl FromLua for crate::light_userdata::LightUserData {
902    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
903        match value {
904            Value::LightUserData(lud) => Ok(lud),
905            other => Err(Error::FromLuaConversionError {
906                from: other.type_name(),
907                to: "LightUserData".to_string(),
908                message: None,
909            }),
910        }
911    }
912}
913
914impl IntoLua for Error {
915    fn into_lua(self, _lua: &Lua) -> Result<Value> {
916        Ok(Value::Error(Box::new(self)))
917    }
918}
919
920impl FromLua for Error {
921    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
922        Ok(match value {
923            Value::Error(e) => *e,
924            // Any other Lua value converts to a runtime error carrying its
925            // string form (mirrors mlua's `convert::<Error>`).
926            Value::String(s) => Error::RuntimeError(s.to_string_lossy()),
927            other => Error::RuntimeError(other.to_string().unwrap_or_default()),
928        })
929    }
930}
931
932/// `Result<T, E>` spreads as the success values on `Ok`, or as `(nil, error)`
933/// on `Err` — mirroring mlua's `IntoLuaMulti for Result`.
934impl<T: IntoLuaMulti, E: IntoLua> IntoLuaMulti for std::result::Result<T, E> {
935    fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
936        match self {
937            Ok(v) => v.into_lua_multi(lua),
938            Err(e) => {
939                let mut m = MultiValue::with_capacity(2);
940                m.push_back(Value::Nil);
941                m.push_back(e.into_lua(lua)?);
942                Ok(m)
943            }
944        }
945    }
946}
947
948// ---------------------------------------------------------------------------
949// MultiValue passthrough
950// ---------------------------------------------------------------------------
951
952impl IntoLuaMulti for MultiValue {
953    fn into_lua_multi(self, _lua: &Lua) -> Result<MultiValue> {
954        Ok(self)
955    }
956}
957
958impl FromLuaMulti for MultiValue {
959    fn from_lua_multi(values: MultiValue, _lua: &Lua) -> Result<Self> {
960        Ok(values)
961    }
962}
963
964// ---------------------------------------------------------------------------
965// Tuples (IntoLuaMulti / FromLuaMulti) up to 12
966// ---------------------------------------------------------------------------
967
968// `IntoLuaMulti` for tuples: each element may itself spread to multiple values
969// (e.g. a trailing `Variadic<T>`), so concatenate their `MultiValue`s.
970macro_rules! impl_tuple_into {
971    () => {};
972    ($first:ident $($rest:ident)*) => {
973        impl_tuple_into!($($rest)*);
974
975        #[allow(non_snake_case)]
976        impl<$first: IntoLuaMulti, $($rest: IntoLuaMulti,)*> IntoLuaMulti for ($first, $($rest,)*) {
977            fn into_lua_multi(self, lua: &Lua) -> Result<MultiValue> {
978                let ($first, $($rest,)*) = self;
979                let mut m = MultiValue::new();
980                for v in $first.into_lua_multi(lua)? { m.push_back(v); }
981                $( for v in $rest.into_lua_multi(lua)? { m.push_back(v); } )*
982                Ok(m)
983            }
984        }
985    };
986}
987
988impl_tuple_into!(A B C D E F G H I J K L);
989
990// `FromLuaMulti` for tuples. The **last** element is parsed as a `FromLuaMulti`
991// (so it may be a trailing `Variadic<T>` that consumes every remaining value);
992// the preceding elements each consume exactly one value via `FromLua`.
993//
994// Because every `FromLua` type is also `FromLuaMulti` (the blanket impl), a
995// single impl per arity with the last slot bound `FromLuaMulti` subsumes the
996// all-`FromLua` case as well — no overlapping impls. Mirrors mlua's tuple
997// `FromLuaMulti`, which lets the final slot soak up the rest.
998macro_rules! impl_tuple_from {
999    // Base: a 1-tuple is just its single `FromLuaMulti` element.
1000    ($last:ident;) => {
1001        #[allow(non_snake_case)]
1002        impl<$last: FromLuaMulti> FromLuaMulti for ($last,) {
1003            fn from_lua_multi(values: MultiValue, lua: &Lua) -> Result<Self> {
1004                Ok(($last::from_lua_multi(values, lua)?,))
1005            }
1006
1007            unsafe fn from_stack_multi(base: c_int, nvals: c_int, lua: &Lua) -> Result<Self> {
1008                Ok((unsafe { $last::from_stack_multi(base, nvals, lua)? },))
1009            }
1010        }
1011    };
1012    ($last:ident; $head0:ident $($head:ident)*) => {
1013        impl_tuple_from!($last; $($head)*);
1014
1015        #[allow(non_snake_case)]
1016        impl<$head0: FromLua, $($head: FromLua,)* $last: FromLuaMulti>
1017            FromLuaMulti for ($head0, $($head,)* $last,)
1018        {
1019            fn from_lua_multi(mut values: MultiValue, lua: &Lua) -> Result<Self> {
1020                let $head0 = $head0::from_lua(values.pop_front().unwrap_or(Value::Nil), lua)?;
1021                $( let $head = $head::from_lua(values.pop_front().unwrap_or(Value::Nil), lua)?; )*
1022                let $last = $last::from_lua_multi(values, lua)?;
1023                Ok(($head0, $($head,)* $last,))
1024            }
1025
1026            unsafe fn from_stack_multi(base: c_int, nvals: c_int, lua: &Lua) -> Result<Self> {
1027                // Walk the stack slots in order: each `FromLua` head reads its
1028                // value directly via `from_stack` (so float fast paths apply
1029                // per element instead of re-materializing a `Value` that folds
1030                // `-0.0`), falling back to Nil past the last result, matching
1031                // the value-level `unwrap_or(Value::Nil)`. The `FromLuaMulti`
1032                // last slot consumes the remainder.
1033                let head_count: c_int = 1 $(+ { let _ = stringify!($head); 1 })*;
1034                let mut idx = base;
1035                let $head0 = {
1036                    idx += 1;
1037                    if idx <= base + nvals {
1038                        unsafe { $head0::from_stack(idx, lua)? }
1039                    } else {
1040                        $head0::from_lua(Value::Nil, lua)?
1041                    }
1042                };
1043                $( let $head = {
1044                    idx += 1;
1045                    if idx <= base + nvals {
1046                        unsafe { $head::from_stack(idx, lua)? }
1047                    } else {
1048                        $head::from_lua(Value::Nil, lua)?
1049                    }
1050                }; )*
1051                let remaining = nvals - head_count;
1052                let $last = unsafe { $last::from_stack_multi(idx, remaining, lua)? };
1053                Ok(($head0, $($head,)* $last,))
1054            }
1055        }
1056    };
1057}
1058
1059// Arities 1..=12 (last element `FromLuaMulti`, the rest `FromLua`).
1060impl_tuple_from!(L; A B C D E F G H I J K);