1- use std:: borrow:: Cow ;
21use std:: fmt:: Debug ;
2+ use std:: sync:: mpsc;
33
4- use rhai:: { Engine , Module , Scope } ;
4+ use rhai:: { Dynamic , Engine , Module , Scope } ;
55
66use crate :: elex:: FunctionPtr ;
77
88#[ derive( Debug ) ]
99pub struct ScriptHost {
1010 pub ( crate ) cmd : String ,
1111 pub ( crate ) history : String ,
12+ log_receiver : mpsc:: Receiver < String > ,
1213 is_active : bool ,
1314 engine : Engine ,
1415 scope : Scope < ' static > ,
@@ -17,10 +18,17 @@ pub struct ScriptHost {
1718impl Default for ScriptHost {
1819 fn default ( ) -> Self {
1920 let mut engine = Engine :: new ( ) ;
21+ let ( tx, tr) = mpsc:: channel ( ) ;
22+
2023 engine. register_static_module ( "game" , ScriptHost :: create_game_module ( ) . into ( ) ) ;
24+ engine. register_fn ( "log" , move |val : Dynamic | {
25+ tx. send ( val. to_string ( ) ) . ok ( ) ;
26+ } ) ;
27+
2128 Self {
2229 cmd : String :: new ( ) ,
2330 history : String :: new ( ) ,
31+ log_receiver : tr,
2432 is_active : false ,
2533 engine,
2634 scope : Scope :: new ( ) ,
@@ -33,19 +41,28 @@ impl ScriptHost {
3341 self . history . push_str ( & self . cmd ) ;
3442 self . history . push ( '\n' ) ;
3543
36- let out = self . handle_command ( ) ;
37- self . history . push_str ( & out) ;
44+ if let Err ( err) = self . engine . run_with_scope ( & mut self . scope , & self . cmd ) {
45+ self . history . push_str ( & err. to_string ( ) ) ;
46+ self . history . push ( '\n' ) ;
47+ }
3848 self . cmd . clear ( ) ;
3949 }
4050
41- fn handle_command ( & mut self ) -> Cow < ' static , str > {
42- let res = self . engine . run_with_scope ( & mut self . scope , & self . cmd ) ;
43- match res {
44- Ok ( ( ) ) => Cow :: Borrowed ( "" ) ,
45- Err ( err) => Cow :: Owned ( err. to_string ( ) + "\n " ) ,
51+ pub fn process_events ( & mut self ) {
52+ while let Ok ( str) = self . log_receiver . try_recv ( ) {
53+ self . history . push_str ( & str) ;
54+ self . history . push ( '\n' ) ;
4655 }
4756 }
4857
58+ pub fn toggle ( & mut self ) {
59+ self . is_active = !self . is_active ;
60+ }
61+
62+ pub fn is_active ( & self ) -> bool {
63+ self . is_active
64+ }
65+
4966 fn create_game_module ( ) -> Module {
5067 let mut module = Module :: new ( ) ;
5168
@@ -58,14 +75,6 @@ impl ScriptHost {
5875 }
5976 module
6077 }
61-
62- pub fn toggle ( & mut self ) {
63- self . is_active = !self . is_active ;
64- }
65-
66- pub fn is_active ( & self ) -> bool {
67- self . is_active
68- }
6978}
7079
7180pub type CustomHandler = fn ( & str , & mut Module , FunctionPtr ) -> u64 ;
0 commit comments