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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::fs::File;
use std::io::prelude::*;
use actor::LuaActor;
use rlua::{Error as LuaError, Lua};
pub struct LuaActorBuilder {
started: Option<String>,
handle: Option<String>,
stopped: Option<String>,
}
impl Default for LuaActorBuilder {
fn default() -> LuaActorBuilder {
let noop = Some("return".to_string());
LuaActorBuilder {
started: noop.clone(),
handle: noop.clone(),
stopped: noop.clone(),
}
}
}
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 build_with_vm(self, vm: Lua) -> Result<LuaActor, LuaError> {
LuaActor::new_with_vm(
vm,
self.started.clone(),
self.handle.clone(),
self.stopped.clone(),
)
}
pub fn build(self) -> Result<LuaActor, LuaError> {
LuaActor::new(
self.started.clone(),
self.handle.clone(),
self.stopped.clone(),
)
}
}
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
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::discriminant;
#[test]
fn build_script_error() {
let res = LuaActorBuilder::new()
.on_handle_with_lua(r"return 1 +")
.build();
if let Err(e) = res {
assert_eq!(
discriminant(&LuaError::RuntimeError("unexpected symbol".to_string())),
discriminant(&e)
);
} else {
panic!("should return error");
}
}
}