Skip to main content

mlua/
conversion.rs

1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
3use std::ffi::{CStr, CString, OsStr, OsString};
4use std::hash::{BuildHasher, Hash};
5use std::os::raw::c_int;
6use std::path::{Path, PathBuf};
7use std::{slice, str};
8
9use bstr::{BStr, BString, ByteVec};
10use num_traits::cast;
11
12use crate::error::{Error, Result};
13use crate::function::Function;
14use crate::state::{Lua, RawLua};
15use crate::string::{BorrowedBytes, BorrowedStr, LuaString};
16use crate::table::Table;
17use crate::thread::Thread;
18use crate::traits::{FromLua, IntoLua, ShortTypeName as _};
19use crate::types::{Either, LightUserData, MaybeSend, MaybeSync, RegistryKey};
20use crate::userdata::{AnyUserData, UserData};
21use crate::value::{Nil, Value};
22
23impl IntoLua for Value {
24    #[inline]
25    fn into_lua(self, _: &Lua) -> Result<Value> {
26        Ok(self)
27    }
28}
29
30impl IntoLua for &Value {
31    #[inline]
32    fn into_lua(self, _: &Lua) -> Result<Value> {
33        Ok(self.clone())
34    }
35
36    #[inline]
37    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
38        lua.push_value(self)
39    }
40}
41
42impl FromLua for Value {
43    #[inline]
44    fn from_lua(lua_value: Value, _: &Lua) -> Result<Self> {
45        Ok(lua_value)
46    }
47}
48
49impl IntoLua for LuaString {
50    #[inline]
51    fn into_lua(self, _: &Lua) -> Result<Value> {
52        Ok(Value::String(self))
53    }
54}
55
56impl IntoLua for &LuaString {
57    #[inline]
58    fn into_lua(self, _: &Lua) -> Result<Value> {
59        Ok(Value::String(self.clone()))
60    }
61
62    #[inline]
63    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
64        lua.push_ref(&self.0);
65        Ok(())
66    }
67}
68
69impl FromLua for LuaString {
70    #[inline]
71    fn from_lua(value: Value, lua: &Lua) -> Result<LuaString> {
72        let ty = value.type_name();
73        lua.coerce_string(value)?
74            .ok_or_else(|| Error::from_lua_conversion(ty, "string", "expected string or number".to_string()))
75    }
76
77    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
78        let state = lua.state();
79        let type_id = ffi::lua_type(state, idx);
80        if type_id == ffi::LUA_TSTRING {
81            ffi::lua_xpush(state, lua.ref_thread(), idx);
82            return Ok(LuaString(lua.pop_ref_thread()));
83        }
84        // Fallback to default
85        Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
86    }
87}
88
89impl IntoLua for BorrowedStr {
90    #[inline]
91    fn into_lua(self, _: &Lua) -> Result<Value> {
92        Ok(Value::String(LuaString(self.vref)))
93    }
94
95    #[inline]
96    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
97        lua.push_ref(&self.vref);
98        Ok(())
99    }
100}
101
102impl IntoLua for &BorrowedStr {
103    #[inline]
104    fn into_lua(self, _: &Lua) -> Result<Value> {
105        Ok(Value::String(LuaString(self.vref.clone())))
106    }
107
108    #[inline]
109    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
110        lua.push_ref(&self.vref);
111        Ok(())
112    }
113}
114
115impl FromLua for BorrowedStr {
116    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
117        let s = LuaString::from_lua(value, lua)?;
118        BorrowedStr::try_from(&s)
119    }
120
121    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
122        let s = LuaString::from_stack(idx, lua)?;
123        BorrowedStr::try_from(&s)
124    }
125}
126
127impl IntoLua for BorrowedBytes {
128    #[inline]
129    fn into_lua(self, _: &Lua) -> Result<Value> {
130        Ok(Value::String(LuaString(self.vref)))
131    }
132
133    #[inline]
134    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
135        lua.push_ref(&self.vref);
136        Ok(())
137    }
138}
139
140impl IntoLua for &BorrowedBytes {
141    #[inline]
142    fn into_lua(self, _: &Lua) -> Result<Value> {
143        Ok(Value::String(LuaString(self.vref.clone())))
144    }
145
146    #[inline]
147    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
148        lua.push_ref(&self.vref);
149        Ok(())
150    }
151}
152
153impl FromLua for BorrowedBytes {
154    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
155        let s = LuaString::from_lua(value, lua)?;
156        Ok(BorrowedBytes::from(&s))
157    }
158
159    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
160        let s = LuaString::from_stack(idx, lua)?;
161        Ok(BorrowedBytes::from(&s))
162    }
163}
164
165impl IntoLua for Table {
166    #[inline]
167    fn into_lua(self, _: &Lua) -> Result<Value> {
168        Ok(Value::Table(self))
169    }
170}
171
172impl IntoLua for &Table {
173    #[inline]
174    fn into_lua(self, _: &Lua) -> Result<Value> {
175        Ok(Value::Table(self.clone()))
176    }
177
178    #[inline]
179    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
180        lua.push_ref(&self.0);
181        Ok(())
182    }
183}
184
185impl FromLua for Table {
186    #[inline]
187    fn from_lua(value: Value, _: &Lua) -> Result<Table> {
188        match value {
189            Value::Table(table) => Ok(table),
190            _ => Err(Error::from_lua_conversion(value.type_name(), "table", None)),
191        }
192    }
193}
194
195impl IntoLua for Function {
196    #[inline]
197    fn into_lua(self, _: &Lua) -> Result<Value> {
198        Ok(Value::Function(self))
199    }
200}
201
202impl IntoLua for &Function {
203    #[inline]
204    fn into_lua(self, _: &Lua) -> Result<Value> {
205        Ok(Value::Function(self.clone()))
206    }
207
208    #[inline]
209    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
210        lua.push_ref(&self.0);
211        Ok(())
212    }
213}
214
215impl FromLua for Function {
216    #[inline]
217    fn from_lua(value: Value, _: &Lua) -> Result<Function> {
218        match value {
219            Value::Function(table) => Ok(table),
220            _ => Err(Error::from_lua_conversion(value.type_name(), "function", None)),
221        }
222    }
223}
224
225impl IntoLua for Thread {
226    #[inline]
227    fn into_lua(self, _: &Lua) -> Result<Value> {
228        Ok(Value::Thread(self))
229    }
230}
231
232impl IntoLua for &Thread {
233    #[inline]
234    fn into_lua(self, _: &Lua) -> Result<Value> {
235        Ok(Value::Thread(self.clone()))
236    }
237
238    #[inline]
239    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
240        lua.push_ref(&self.0);
241        Ok(())
242    }
243}
244
245impl FromLua for Thread {
246    #[inline]
247    fn from_lua(value: Value, _: &Lua) -> Result<Thread> {
248        match value {
249            Value::Thread(t) => Ok(t),
250            _ => Err(Error::from_lua_conversion(value.type_name(), "thread", None)),
251        }
252    }
253}
254
255impl IntoLua for AnyUserData {
256    #[inline]
257    fn into_lua(self, _: &Lua) -> Result<Value> {
258        Ok(Value::UserData(self))
259    }
260}
261
262impl IntoLua for &AnyUserData {
263    #[inline]
264    fn into_lua(self, _: &Lua) -> Result<Value> {
265        Ok(Value::UserData(self.clone()))
266    }
267
268    #[inline]
269    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
270        lua.push_ref(&self.0);
271        Ok(())
272    }
273}
274
275impl FromLua for AnyUserData {
276    #[inline]
277    fn from_lua(value: Value, _: &Lua) -> Result<AnyUserData> {
278        match value {
279            Value::UserData(ud) => Ok(ud),
280            _ => Err(Error::from_lua_conversion(value.type_name(), "userdata", None)),
281        }
282    }
283}
284
285impl<T: UserData + MaybeSend + MaybeSync + 'static> IntoLua for T {
286    #[inline]
287    fn into_lua(self, lua: &Lua) -> Result<Value> {
288        Ok(Value::UserData(lua.create_userdata(self)?))
289    }
290}
291
292impl IntoLua for Error {
293    #[inline]
294    fn into_lua(self, _: &Lua) -> Result<Value> {
295        Ok(Value::Error(Box::new(self)))
296    }
297}
298
299impl FromLua for Error {
300    #[inline]
301    fn from_lua(value: Value, _: &Lua) -> Result<Error> {
302        match value {
303            Value::Error(err) => Ok(*err),
304            val => Ok(Error::runtime(val.to_string()?)),
305        }
306    }
307}
308
309#[cfg(feature = "anyhow")]
310impl IntoLua for anyhow::Error {
311    #[inline]
312    fn into_lua(self, _: &Lua) -> Result<Value> {
313        Ok(Value::Error(Box::new(Error::from(self))))
314    }
315}
316
317impl IntoLua for RegistryKey {
318    #[inline]
319    fn into_lua(self, lua: &Lua) -> Result<Value> {
320        lua.registry_value(&self)
321    }
322
323    #[inline]
324    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
325        <&RegistryKey>::push_into_stack(&self, lua)
326    }
327}
328
329impl IntoLua for &RegistryKey {
330    #[inline]
331    fn into_lua(self, lua: &Lua) -> Result<Value> {
332        lua.registry_value(self)
333    }
334
335    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
336        if !lua.owns_registry_value(self) {
337            return Err(Error::MismatchedRegistryKey);
338        }
339
340        match self.id() {
341            ffi::LUA_REFNIL => ffi::lua_pushnil(lua.state()),
342            id => {
343                ffi::lua_rawgeti(lua.state(), ffi::LUA_REGISTRYINDEX, id as _);
344            }
345        }
346        Ok(())
347    }
348}
349
350impl FromLua for RegistryKey {
351    #[inline]
352    fn from_lua(value: Value, lua: &Lua) -> Result<RegistryKey> {
353        lua.create_registry_value(value)
354    }
355}
356
357impl IntoLua for bool {
358    #[inline]
359    fn into_lua(self, _: &Lua) -> Result<Value> {
360        Ok(Value::Boolean(self))
361    }
362
363    #[inline]
364    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
365        ffi::lua_pushboolean(lua.state(), self as c_int);
366        Ok(())
367    }
368}
369
370impl FromLua for bool {
371    #[inline]
372    fn from_lua(v: Value, _: &Lua) -> Result<Self> {
373        match v {
374            Value::Nil => Ok(false),
375            Value::Boolean(b) => Ok(b),
376            _ => Ok(true),
377        }
378    }
379
380    #[inline]
381    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
382        Ok(ffi::lua_toboolean(lua.state(), idx) != 0)
383    }
384}
385
386impl IntoLua for LightUserData {
387    #[inline]
388    fn into_lua(self, _: &Lua) -> Result<Value> {
389        Ok(Value::LightUserData(self))
390    }
391}
392
393impl FromLua for LightUserData {
394    #[inline]
395    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
396        match value {
397            Value::LightUserData(ud) => Ok(ud),
398            _ => Err(Error::from_lua_conversion(
399                value.type_name(),
400                "lightuserdata",
401                None,
402            )),
403        }
404    }
405}
406
407#[cfg(feature = "luau")]
408impl IntoLua for crate::Vector {
409    #[inline]
410    fn into_lua(self, _: &Lua) -> Result<Value> {
411        Ok(Value::Vector(self))
412    }
413}
414
415#[cfg(feature = "luau")]
416impl FromLua for crate::Vector {
417    #[inline]
418    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
419        match value {
420            Value::Vector(v) => Ok(v),
421            _ => Err(Error::from_lua_conversion(value.type_name(), "vector", None)),
422        }
423    }
424}
425
426#[cfg(feature = "luau")]
427impl IntoLua for crate::Buffer {
428    #[inline]
429    fn into_lua(self, _: &Lua) -> Result<Value> {
430        Ok(Value::Buffer(self))
431    }
432}
433
434#[cfg(feature = "luau")]
435impl IntoLua for &crate::Buffer {
436    #[inline]
437    fn into_lua(self, _: &Lua) -> Result<Value> {
438        Ok(Value::Buffer(self.clone()))
439    }
440
441    #[inline]
442    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
443        lua.push_ref(&self.0);
444        Ok(())
445    }
446}
447
448#[cfg(feature = "luau")]
449impl FromLua for crate::Buffer {
450    #[inline]
451    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
452        match value {
453            Value::Buffer(buf) => Ok(buf),
454            _ => Err(Error::from_lua_conversion(value.type_name(), "buffer", None)),
455        }
456    }
457}
458
459impl IntoLua for String {
460    #[inline]
461    fn into_lua(self, lua: &Lua) -> Result<Value> {
462        #[cfg(feature = "lua55")]
463        if true {
464            return Ok(Value::String(lua.create_external_string(self)?));
465        }
466
467        Ok(Value::String(lua.create_string(self)?))
468    }
469
470    #[inline]
471    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
472        #[cfg(feature = "lua55")]
473        if lua.unlikely_memory_error() {
474            return crate::util::push_external_string(lua.state(), self.into(), false);
475        }
476
477        push_bytes_into_stack(self, lua)
478    }
479}
480
481impl FromLua for String {
482    #[inline]
483    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
484        let ty = value.type_name();
485        Ok(lua
486            .coerce_string(value)?
487            .ok_or_else(|| {
488                Error::from_lua_conversion(ty, Self::type_name(), "expected string or number".to_string())
489            })?
490            .to_str()?
491            .to_owned())
492    }
493
494    #[inline]
495    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
496        let state = lua.state();
497        let type_id = ffi::lua_type(state, idx);
498        if type_id == ffi::LUA_TSTRING {
499            let mut size = 0;
500            let data = ffi::lua_tolstring(state, idx, &mut size);
501            let bytes = slice::from_raw_parts(data as *const u8, size);
502            return str::from_utf8(bytes)
503                .map(|s| s.to_owned())
504                .map_err(|e| Error::from_lua_conversion("string", Self::type_name(), e.to_string()));
505        }
506        // Fallback to default
507        Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
508    }
509}
510
511impl IntoLua for &str {
512    #[inline]
513    fn into_lua(self, lua: &Lua) -> Result<Value> {
514        Ok(Value::String(lua.create_string(self)?))
515    }
516
517    #[inline]
518    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
519        push_bytes_into_stack(self, lua)
520    }
521}
522
523impl IntoLua for Cow<'_, str> {
524    #[inline]
525    fn into_lua(self, lua: &Lua) -> Result<Value> {
526        Ok(Value::String(lua.create_string(self.as_bytes())?))
527    }
528}
529
530impl IntoLua for Box<str> {
531    #[inline]
532    fn into_lua(self, lua: &Lua) -> Result<Value> {
533        Ok(Value::String(lua.create_string(&*self)?))
534    }
535}
536
537impl FromLua for Box<str> {
538    #[inline]
539    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
540        let ty = value.type_name();
541        Ok(lua
542            .coerce_string(value)?
543            .ok_or_else(|| {
544                Error::from_lua_conversion(ty, Self::type_name(), "expected string or number".to_string())
545            })?
546            .to_str()?
547            .to_owned()
548            .into_boxed_str())
549    }
550}
551
552impl IntoLua for CString {
553    #[inline]
554    fn into_lua(self, lua: &Lua) -> Result<Value> {
555        #[cfg(feature = "lua55")]
556        if true {
557            return Ok(Value::String(lua.create_external_string(self)?));
558        }
559
560        Ok(Value::String(lua.create_string(self.as_bytes())?))
561    }
562}
563
564impl FromLua for CString {
565    #[inline]
566    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
567        let ty = value.type_name();
568        let string = lua.coerce_string(value)?.ok_or_else(|| {
569            Error::from_lua_conversion(ty, Self::type_name(), "expected string or number".to_string())
570        })?;
571        match CStr::from_bytes_with_nul(&string.as_bytes_with_nul()) {
572            Ok(s) => Ok(s.into()),
573            Err(err) => Err(Error::from_lua_conversion(ty, Self::type_name(), err.to_string())),
574        }
575    }
576}
577
578impl IntoLua for &CStr {
579    #[inline]
580    fn into_lua(self, lua: &Lua) -> Result<Value> {
581        Ok(Value::String(lua.create_string(self.to_bytes())?))
582    }
583}
584
585impl IntoLua for Cow<'_, CStr> {
586    #[inline]
587    fn into_lua(self, lua: &Lua) -> Result<Value> {
588        Ok(Value::String(lua.create_string(self.to_bytes())?))
589    }
590}
591
592impl IntoLua for BString {
593    #[inline]
594    fn into_lua(self, lua: &Lua) -> Result<Value> {
595        #[cfg(feature = "lua55")]
596        if true {
597            return Ok(Value::String(lua.create_external_string(self)?));
598        }
599
600        Ok(Value::String(lua.create_string(self)?))
601    }
602}
603
604impl FromLua for BString {
605    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
606        let ty = value.type_name();
607        match value {
608            Value::String(s) => Ok((*s.as_bytes()).into()),
609            #[cfg(feature = "luau")]
610            Value::Buffer(buf) => Ok(buf.to_vec().into()),
611            _ => Ok((*lua
612                .coerce_string(value)?
613                .ok_or_else(|| {
614                    Error::from_lua_conversion(ty, Self::type_name(), "expected string or number".to_string())
615                })?
616                .as_bytes())
617            .into()),
618        }
619    }
620
621    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
622        let state = lua.state();
623        match ffi::lua_type(state, idx) {
624            ffi::LUA_TSTRING => {
625                let mut size = 0;
626                let data = ffi::lua_tolstring(state, idx, &mut size);
627                Ok(slice::from_raw_parts(data as *const u8, size).into())
628            }
629            #[cfg(feature = "luau")]
630            ffi::LUA_TBUFFER => {
631                let mut size = 0;
632                let buf = ffi::lua_tobuffer(state, idx, &mut size);
633                mlua_assert!(!buf.is_null(), "invalid Luau buffer");
634                Ok(slice::from_raw_parts(buf as *const u8, size).into())
635            }
636            type_id => {
637                // Fallback to default
638                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
639            }
640        }
641    }
642}
643
644impl IntoLua for &BStr {
645    #[inline]
646    fn into_lua(self, lua: &Lua) -> Result<Value> {
647        Ok(Value::String(lua.create_string(self)?))
648    }
649}
650
651impl IntoLua for OsString {
652    #[inline]
653    fn into_lua(self, lua: &Lua) -> Result<Value> {
654        self.as_os_str().into_lua(lua)
655    }
656}
657
658impl FromLua for OsString {
659    #[inline]
660    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
661        let ty = value.type_name();
662        let bs = BString::from_lua(value, lua)?;
663        Vec::from(bs)
664            .into_os_string()
665            .map_err(|err| Error::from_lua_conversion(ty, "OsString", err.to_string()))
666    }
667}
668
669impl IntoLua for &OsStr {
670    #[cfg(unix)]
671    #[inline]
672    fn into_lua(self, lua: &Lua) -> Result<Value> {
673        use std::os::unix::ffi::OsStrExt;
674        Ok(Value::String(lua.create_string(self.as_bytes())?))
675    }
676
677    #[cfg(not(unix))]
678    #[inline]
679    fn into_lua(self, lua: &Lua) -> Result<Value> {
680        self.display().to_string().into_lua(lua)
681    }
682}
683
684impl IntoLua for PathBuf {
685    #[inline]
686    fn into_lua(self, lua: &Lua) -> Result<Value> {
687        self.as_os_str().into_lua(lua)
688    }
689}
690
691impl FromLua for PathBuf {
692    #[inline]
693    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
694        OsString::from_lua(value, lua).map(PathBuf::from)
695    }
696}
697
698impl IntoLua for &Path {
699    #[inline]
700    fn into_lua(self, lua: &Lua) -> Result<Value> {
701        self.as_os_str().into_lua(lua)
702    }
703}
704
705impl IntoLua for char {
706    #[inline]
707    fn into_lua(self, lua: &Lua) -> Result<Value> {
708        let mut char_bytes = [0; 4];
709        self.encode_utf8(&mut char_bytes);
710        Ok(Value::String(lua.create_string(&char_bytes[..self.len_utf8()])?))
711    }
712}
713
714impl FromLua for char {
715    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
716        let ty = value.type_name();
717        match value {
718            Value::Integer(i) => cast(i).and_then(char::from_u32).ok_or_else(|| {
719                let msg = "integer out of range when converting to char";
720                Error::from_lua_conversion(ty, "char", msg.to_string())
721            }),
722            Value::String(s) => {
723                let str = s.to_str()?;
724                let mut str_iter = str.chars();
725                match (str_iter.next(), str_iter.next()) {
726                    (Some(char), None) => Ok(char),
727                    _ => {
728                        let msg = "expected string to have exactly one char when converting to char";
729                        Err(Error::from_lua_conversion(ty, "char", msg.to_string()))
730                    }
731                }
732            }
733            _ => {
734                let msg = "expected string or integer";
735                Err(Error::from_lua_conversion(ty, Self::type_name(), msg.to_string()))
736            }
737        }
738    }
739}
740
741#[inline]
742unsafe fn push_bytes_into_stack<T>(this: T, lua: &RawLua) -> Result<()>
743where
744    T: IntoLua + AsRef<[u8]>,
745{
746    let bytes = this.as_ref();
747    if lua.unlikely_memory_error() && bytes.len() < (1 << 30) {
748        // Fast path: push directly into the Lua stack.
749        ffi::lua_pushlstring(lua.state(), bytes.as_ptr() as *const _, bytes.len());
750        return Ok(());
751    }
752    // Fallback to default
753    lua.push_value(&T::into_lua(this, lua.lua())?)
754}
755
756macro_rules! lua_convert_int {
757    ($x:ty) => {
758        impl IntoLua for $x {
759            #[inline]
760            fn into_lua(self, _: &Lua) -> Result<Value> {
761                Ok(cast(self)
762                    .map(Value::Integer)
763                    .unwrap_or_else(|| Value::Number(self as ffi::lua_Number)))
764            }
765
766            #[inline]
767            unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
768                match cast(self) {
769                    Some(i) => ffi::lua_pushinteger(lua.state(), i),
770                    None => ffi::lua_pushnumber(lua.state(), self as ffi::lua_Number),
771                }
772                Ok(())
773            }
774        }
775
776        impl FromLua for $x {
777            #[inline]
778            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
779                let ty = value.type_name();
780                (match value {
781                    Value::Integer(i) => cast(i),
782                    Value::Number(n) => cast(n),
783                    _ => {
784                        if let Some(i) = lua.coerce_integer(value.clone())? {
785                            cast(i)
786                        } else {
787                            cast(lua.coerce_number(value)?.ok_or_else(|| {
788                                let msg = "expected number or string coercible to number";
789                                Error::from_lua_conversion(ty, stringify!($x), msg.to_string())
790                            })?)
791                        }
792                    }
793                })
794                .ok_or_else(|| Error::from_lua_conversion(ty, stringify!($x), "out of range".to_string()))
795            }
796
797            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
798                let state = lua.state();
799                let type_id = ffi::lua_type(state, idx);
800                if type_id == ffi::LUA_TNUMBER {
801                    let mut ok = 0;
802                    let i = ffi::lua_tointegerx(state, idx, &mut ok);
803                    if ok != 0 {
804                        return cast(i).ok_or_else(|| {
805                            Error::from_lua_conversion("integer", stringify!($x), "out of range".to_string())
806                        });
807                    }
808                }
809                // Fallback to default
810                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
811            }
812        }
813    };
814}
815
816lua_convert_int!(i8);
817lua_convert_int!(u8);
818lua_convert_int!(i16);
819lua_convert_int!(u16);
820lua_convert_int!(i32);
821lua_convert_int!(u32);
822lua_convert_int!(i64);
823lua_convert_int!(u64);
824lua_convert_int!(i128);
825lua_convert_int!(u128);
826lua_convert_int!(isize);
827lua_convert_int!(usize);
828
829macro_rules! lua_convert_float {
830    ($x:ty) => {
831        impl IntoLua for $x {
832            #[inline]
833            fn into_lua(self, _: &Lua) -> Result<Value> {
834                Ok(Value::Number(self as _))
835            }
836        }
837
838        impl FromLua for $x {
839            #[inline]
840            fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
841                let ty = value.type_name();
842                lua.coerce_number(value)?.map(|n| n as $x).ok_or_else(|| {
843                    let msg = "expected number or string coercible to number";
844                    Error::from_lua_conversion(ty, stringify!($x), msg.to_string())
845                })
846            }
847
848            unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
849                let state = lua.state();
850                let type_id = ffi::lua_type(state, idx);
851                if type_id == ffi::LUA_TNUMBER {
852                    return Ok(ffi::lua_tonumber(state, idx) as _);
853                }
854                // Fallback to default
855                Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
856            }
857        }
858    };
859}
860
861lua_convert_float!(f32);
862lua_convert_float!(f64);
863
864impl<T> IntoLua for &[T]
865where
866    T: IntoLua + Clone,
867{
868    #[inline]
869    fn into_lua(self, lua: &Lua) -> Result<Value> {
870        Ok(Value::Table(lua.create_sequence_from(self.iter().cloned())?))
871    }
872}
873
874impl<T, const N: usize> IntoLua for [T; N]
875where
876    T: IntoLua,
877{
878    #[inline]
879    fn into_lua(self, lua: &Lua) -> Result<Value> {
880        Ok(Value::Table(lua.create_sequence_from(self)?))
881    }
882}
883
884impl<T, const N: usize> FromLua for [T; N]
885where
886    T: FromLua,
887{
888    #[inline]
889    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
890        match value {
891            #[cfg(feature = "luau")]
892            #[rustfmt::skip]
893            Value::Vector(v) if N == crate::Vector::SIZE => unsafe {
894                use std::{mem, ptr};
895                let mut arr: [mem::MaybeUninit<T>; N] = mem::MaybeUninit::uninit().assume_init();
896                ptr::write(arr[0].as_mut_ptr() , T::from_lua(Value::Number(v.x() as _), _lua)?);
897                ptr::write(arr[1].as_mut_ptr(), T::from_lua(Value::Number(v.y() as _), _lua)?);
898                ptr::write(arr[2].as_mut_ptr(), T::from_lua(Value::Number(v.z() as _), _lua)?);
899                #[cfg(feature = "luau-vector4")]
900                ptr::write(arr[3].as_mut_ptr(), T::from_lua(Value::Number(v.w() as _), _lua)?);
901                Ok(mem::transmute_copy(&arr))
902            },
903            Value::Table(table) => {
904                let vec = table.sequence_values().collect::<Result<Vec<_>>>()?;
905                vec.try_into().map_err(|vec: Vec<T>| {
906                    let msg = format!("expected table of length {N}, got {}", vec.len());
907                    Error::from_lua_conversion("table", Self::type_name(), msg)
908                })
909            }
910            _ => {
911                let msg = format!("expected table of length {N}");
912                let err = Error::from_lua_conversion(value.type_name(), Self::type_name(), msg.to_string());
913                Err(err)
914            }
915        }
916    }
917}
918
919impl<T: IntoLua> IntoLua for Box<[T]> {
920    #[inline]
921    fn into_lua(self, lua: &Lua) -> Result<Value> {
922        Ok(Value::Table(lua.create_sequence_from(self.into_vec())?))
923    }
924}
925
926impl<T: FromLua> FromLua for Box<[T]> {
927    #[inline]
928    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
929        Ok(Vec::<T>::from_lua(value, lua)?.into_boxed_slice())
930    }
931}
932
933impl<T: IntoLua> IntoLua for Vec<T> {
934    #[inline]
935    fn into_lua(self, lua: &Lua) -> Result<Value> {
936        Ok(Value::Table(lua.create_sequence_from(self)?))
937    }
938}
939
940impl<T: FromLua> FromLua for Vec<T> {
941    #[inline]
942    fn from_lua(value: Value, _lua: &Lua) -> Result<Self> {
943        match value {
944            Value::Table(table) => table.sequence_values().collect(),
945            _ => Err(Error::from_lua_conversion(
946                value.type_name(),
947                Self::type_name(),
948                "expected table".to_string(),
949            )),
950        }
951    }
952}
953
954impl<K: Eq + Hash + IntoLua, V: IntoLua, S: BuildHasher> IntoLua for HashMap<K, V, S> {
955    #[inline]
956    fn into_lua(self, lua: &Lua) -> Result<Value> {
957        Ok(Value::Table(lua.create_table_from(self)?))
958    }
959}
960
961impl<K: Eq + Hash + FromLua, V: FromLua, S: BuildHasher + Default> FromLua for HashMap<K, V, S> {
962    #[inline]
963    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
964        match value {
965            Value::Table(table) => table.pairs().collect(),
966            _ => Err(Error::from_lua_conversion(
967                value.type_name(),
968                Self::type_name(),
969                "expected table".to_string(),
970            )),
971        }
972    }
973}
974
975impl<K: Ord + IntoLua, V: IntoLua> IntoLua for BTreeMap<K, V> {
976    #[inline]
977    fn into_lua(self, lua: &Lua) -> Result<Value> {
978        Ok(Value::Table(lua.create_table_from(self)?))
979    }
980}
981
982impl<K: Ord + FromLua, V: FromLua> FromLua for BTreeMap<K, V> {
983    #[inline]
984    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
985        match value {
986            Value::Table(table) => table.pairs().collect(),
987            _ => Err(Error::from_lua_conversion(
988                value.type_name(),
989                Self::type_name(),
990                "expected table".to_string(),
991            )),
992        }
993    }
994}
995
996impl<T: Eq + Hash + IntoLua, S: BuildHasher> IntoLua for HashSet<T, S> {
997    #[inline]
998    fn into_lua(self, lua: &Lua) -> Result<Value> {
999        Ok(Value::Table(
1000            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1001        ))
1002    }
1003}
1004
1005impl<T: Eq + Hash + FromLua, S: BuildHasher + Default> FromLua for HashSet<T, S> {
1006    #[inline]
1007    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1008        match value {
1009            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1010            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1011            _ => Err(Error::from_lua_conversion(
1012                value.type_name(),
1013                Self::type_name(),
1014                "expected table".to_string(),
1015            )),
1016        }
1017    }
1018}
1019
1020impl<T: Ord + IntoLua> IntoLua for BTreeSet<T> {
1021    #[inline]
1022    fn into_lua(self, lua: &Lua) -> Result<Value> {
1023        Ok(Value::Table(
1024            lua.create_table_from(self.into_iter().map(|val| (val, true)))?,
1025        ))
1026    }
1027}
1028
1029impl<T: Ord + FromLua> FromLua for BTreeSet<T> {
1030    #[inline]
1031    fn from_lua(value: Value, _: &Lua) -> Result<Self> {
1032        match value {
1033            Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(),
1034            Value::Table(table) => table.pairs::<T, Value>().map(|res| res.map(|(k, _)| k)).collect(),
1035            _ => Err(Error::from_lua_conversion(
1036                value.type_name(),
1037                Self::type_name(),
1038                "expected table".to_string(),
1039            )),
1040        }
1041    }
1042}
1043
1044impl<T: IntoLua> IntoLua for Option<T> {
1045    #[inline]
1046    fn into_lua(self, lua: &Lua) -> Result<Value> {
1047        match self {
1048            Some(val) => val.into_lua(lua),
1049            None => Ok(Nil),
1050        }
1051    }
1052
1053    #[inline]
1054    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1055        match self {
1056            Some(val) => val.push_into_stack(lua)?,
1057            None => ffi::lua_pushnil(lua.state()),
1058        }
1059        Ok(())
1060    }
1061}
1062
1063impl<T: FromLua> FromLua for Option<T> {
1064    #[inline]
1065    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1066        match value {
1067            Nil => Ok(None),
1068            value => Ok(Some(T::from_lua(value, lua)?)),
1069        }
1070    }
1071
1072    #[inline]
1073    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1074        match ffi::lua_type(lua.state(), idx) {
1075            ffi::LUA_TNIL => Ok(None),
1076            _ => Ok(Some(T::from_stack(idx, lua)?)),
1077        }
1078    }
1079}
1080
1081impl<L: IntoLua, R: IntoLua> IntoLua for Either<L, R> {
1082    #[inline]
1083    fn into_lua(self, lua: &Lua) -> Result<Value> {
1084        match self {
1085            Either::Left(l) => l.into_lua(lua),
1086            Either::Right(r) => r.into_lua(lua),
1087        }
1088    }
1089
1090    #[inline]
1091    unsafe fn push_into_stack(self, lua: &RawLua) -> Result<()> {
1092        match self {
1093            Either::Left(l) => l.push_into_stack(lua),
1094            Either::Right(r) => r.push_into_stack(lua),
1095        }
1096    }
1097}
1098
1099impl<L: FromLua, R: FromLua> FromLua for Either<L, R> {
1100    #[inline]
1101    fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
1102        let value_type_name = value.type_name();
1103        // Try the left type first
1104        match L::from_lua(value.clone(), lua) {
1105            Ok(l) => Ok(Either::Left(l)),
1106            // Try the right type
1107            Err(_) => match R::from_lua(value, lua).map(Either::Right) {
1108                Ok(r) => Ok(r),
1109                Err(_) => Err(Error::from_lua_conversion(
1110                    value_type_name,
1111                    Self::type_name(),
1112                    None,
1113                )),
1114            },
1115        }
1116    }
1117
1118    #[inline]
1119    unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
1120        match L::from_stack(idx, lua) {
1121            Ok(l) => Ok(Either::Left(l)),
1122            Err(_) => match R::from_stack(idx, lua).map(Either::Right) {
1123                Ok(r) => Ok(r),
1124                Err(_) => {
1125                    let state = lua.state();
1126                    let from_type_name = CStr::from_ptr(ffi::lua_typename(state, ffi::lua_type(state, idx)))
1127                        .to_str()
1128                        .unwrap_or("unknown");
1129                    let err = Error::from_lua_conversion(from_type_name, Self::type_name(), None);
1130                    Err(err)
1131                }
1132            },
1133        }
1134    }
1135}