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
use crate::lua_generator::{LuaGenerator, ToLua}; use crate::nodes::Block; #[derive(Clone, Debug, PartialEq, Eq)] pub struct FunctionExpression { block: Block, parameters: Vec<String>, is_variadic: bool, } impl FunctionExpression { pub fn new(block: Block, parameters: Vec<String>, is_variadic: bool) -> Self { Self { block, parameters, is_variadic, } } pub fn append_parameter(mut self, parameter: String) -> Self { self.parameters.push(parameter); self } pub fn set_variadic(mut self, is_variadic: bool) -> Self { self.is_variadic = is_variadic; self } pub fn mutate_block(&mut self) -> &mut Block { &mut self.block } } impl Default for FunctionExpression { fn default() -> Self { Self { block: Block::default(), parameters: Vec::new(), is_variadic: false, } } } impl ToLua for FunctionExpression { fn to_lua(&self, generator: &mut LuaGenerator) { generator.push_str("function"); generator.push_char('('); generator.for_each_and_between( &self.parameters, |generator, parameter| generator.push_str(parameter), |generator| generator.push_char(','), ); if self.is_variadic { if self.parameters.len() > 0 { generator.push_char(','); }; generator.push_str("..."); }; generator.push_char(')'); self.block.to_lua(generator); generator.push_str("end"); } } #[cfg(test)] mod test { use super::*; #[test] fn generate_empty_function_expression() { let output = FunctionExpression::default().to_lua_string(); assert_eq!(output, "function()end"); } #[test] fn generate_empty_variadic_function_expression() { let output = FunctionExpression::default() .set_variadic(true) .to_lua_string(); assert_eq!(output, "function(...)end"); } #[test] fn generate_empty_variadic_function_with_one_parameter() { let output = FunctionExpression::default() .append_parameter("a".to_owned()) .set_variadic(true) .to_lua_string(); assert_eq!(output, "function(a,...)end"); } #[test] fn generate_empty_variadic_function_with_two_parameter() { let output = FunctionExpression::default() .append_parameter("a".to_owned()) .append_parameter("b".to_owned()) .set_variadic(true) .to_lua_string(); assert_eq!(output, "function(a,b,...)end"); } #[test] fn generate_empty_function_with_two_parameter() { let output = FunctionExpression::default() .append_parameter("a".to_owned()) .append_parameter("b".to_owned()) .to_lua_string(); assert_eq!(output, "function(a,b)end"); } }