worldwideportal/src/command_handler.rs

74 lines
2.5 KiB
Rust
Raw Normal View History

use itertools::join;
use crate::{
echo_to_term_frame, lua_state::LuaState, parsing::parse_commands, GlobalCell, TermFrame,
};
fn debrace(inp: &str) -> &str {
let v = inp.trim();
if v.starts_with("{") && v.ends_with("}") {
&v[1..(v.len() - 1)]
} else {
v
}
}
fn reentrant_command_handler(
lua_state: &mut LuaState,
globals: &GlobalCell,
term_frame: &TermFrame,
command_in: &str,
) {
2024-08-17 16:42:01 +10:00
echo_to_term_frame(globals, term_frame, "\r").unwrap_or(());
lua_state.set_current_frame(term_frame);
for command in parse_commands(command_in).commands {
match command.split_out_command() {
None => (),
Some((cmd, rest)) => {
2024-08-18 20:58:50 +10:00
if let ("#", command_rest) = cmd.split_at(1) {
if cmd == "##" {
match lua_state.execute(debrace(&join(rest.arguments.iter(), " "))) {
Ok(()) => (),
Err(msg) => {
echo_to_term_frame(globals, term_frame, &format!("{}\r\n", msg))
.unwrap_or(())
}
}
2024-08-18 20:58:50 +10:00
} else if let Ok(repeat_count) = command_rest.parse::<u16>() {
for _ in 0..repeat_count {
reentrant_command_handler(
lua_state,
globals,
term_frame,
&join(rest.arguments.iter(), " "),
);
}
} else {
2024-08-18 20:58:50 +10:00
match lua_state.execute_command(command_rest, &rest.arguments) {
Ok(()) => (),
Err(msg) => {
echo_to_term_frame(globals, term_frame, &format!("{}\r\n", msg))
.unwrap_or(())
}
2024-08-17 16:42:01 +10:00
}
}
}
}
}
}
}
pub fn command_handler(globals: &GlobalCell, term_frame: &TermFrame, command_in: &str) {
match globals.lua_engine.try_borrow_mut() {
Err(_) => echo_to_term_frame(
globals,
term_frame,
2024-08-17 16:42:01 +10:00
"Attempt to re-enter command handler during processing.\r\n",
)
.unwrap_or(()), // Ignore error handling error.
Ok(mut lua_state_m) => {
reentrant_command_handler(&mut lua_state_m, globals, term_frame, command_in)
}
}
}