1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
use std::fs::File; use std::io::prelude::*; use actor::LuaActor; use rlua::{Error as LuaError, Lua}; pub type InitializeVM = Fn(&Lua) -> Result<(), LuaError>; pub struct LuaActorBuilder { started: Option<String>, handle: Option<String>, stopped: Option<String>, initialize_vm: Option<Box<InitializeVM>>, } impl Default for LuaActorBuilder { fn default() -> LuaActorBuilder { let noop = Some("return".to_string()); LuaActorBuilder { started: noop.clone(), handle: noop.clone(), stopped: noop.clone(), initialize_vm: None, } } } impl LuaActorBuilder { pub fn new() -> Self { LuaActorBuilder::default() } pub fn on_started(mut self, filename: &str) -> Self { self.started = Some(read_to_string(filename)); self } pub fn on_started_with_lua(mut self, script: &str) -> Self { self.started = Some(script.to_string()); self } pub fn on_handle(mut self, filename: &str) -> Self { self.handle = Some(read_to_string(filename)); self } pub fn on_handle_with_lua(mut self, script: &str) -> Self { self.handle = Some(script.to_string()); self } pub fn on_stopped(mut self, filename: &str) -> Self { self.stopped = Some(read_to_string(filename)); self } pub fn on_stopped_with_lua(mut self, script: &str) -> Self { self.stopped = Some(script.to_string()); self } pub fn with_vm<F: Fn(&Lua) -> Result<(), LuaError> + 'static>(mut self, callback: F) -> Self { self.initialize_vm = Some(Box::new(callback)); self } pub fn build(self) -> Result<LuaActor, LuaError> { LuaActor::new( self.started.clone(), self.handle.clone(), self.stopped.clone(), self.initialize_vm, ) } } fn read_to_string(filename: &str) -> String { let mut f = File::open(filename).expect("File not found"); let mut body = String::new(); f.read_to_string(&mut body).expect("Failed to read file"); body }