@@ -655,6 +655,71 @@ impl IntoLua for &Path {
655
655
}
656
656
}
657
657
658
+ impl IntoLua for char {
659
+ #[ inline]
660
+ fn into_lua ( self , lua : & Lua ) -> Result < Value > {
661
+ let mut char_bytes = [ 0 ; 4 ] ;
662
+ self . encode_utf8 ( & mut char_bytes) ;
663
+ Ok ( Value :: String ( lua. create_string ( char_bytes) ?) )
664
+ }
665
+ }
666
+
667
+ impl FromLua for char {
668
+ #[ inline]
669
+ fn from_lua ( value : Value , _lua : & Lua ) -> Result < Self > {
670
+ let ty = value. type_name ( ) ;
671
+ match value {
672
+ // When integer: reduce it to u8 and try to convert to char
673
+ Value :: Integer ( i) => {
674
+ if i <= u8:: MAX . into ( ) && i >= 0 {
675
+ Ok ( char:: from ( i as u8 ) )
676
+ } else {
677
+ Err ( Error :: FromLuaConversionError {
678
+ from : ty,
679
+ to : Self :: type_name ( ) ,
680
+ message : Some (
681
+ "expected int to be a u8 when converting to char. You can also use strings."
682
+ . to_string ( ) ,
683
+ ) ,
684
+ } )
685
+ }
686
+ }
687
+ // When String: first char, and only if there is one char
688
+ Value :: String ( s) => {
689
+ let str = s. to_str ( ) ?;
690
+ let mut str_iter = str. chars ( ) ;
691
+ let Some ( char) = str_iter. next ( ) else {
692
+ return Err ( Error :: FromLuaConversionError {
693
+ from : ty,
694
+ to : Self :: type_name ( ) ,
695
+ message : Some (
696
+ "string must have one char when converting to char. (empty string)" . to_string ( ) ,
697
+ ) ,
698
+ } ) ;
699
+ } ;
700
+
701
+ if let Some ( _extra_char) = str_iter. next ( ) {
702
+ Err ( Error :: FromLuaConversionError {
703
+ from : ty,
704
+ to : Self :: type_name ( ) ,
705
+ message : Some (
706
+ "expected lua string to have exactly one char when converting to char"
707
+ . to_string ( ) ,
708
+ ) ,
709
+ } )
710
+ } else {
711
+ Ok ( char)
712
+ }
713
+ }
714
+ _ => Err ( Error :: FromLuaConversionError {
715
+ from : ty,
716
+ to : Self :: type_name ( ) ,
717
+ message : Some ( "expected string or integer" . to_string ( ) ) ,
718
+ } ) ,
719
+ }
720
+ }
721
+ }
722
+
658
723
#[ inline]
659
724
unsafe fn push_bytes_into_stack < T > ( this : T , lua : & RawLua ) -> Result < ( ) >
660
725
where
0 commit comments