summaryrefslogtreecommitdiff
path: root/examples/repl.rs
blob: ff634c7835443ec9213dc49a62384836d6cc6547 (plain)
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
//! This example shows a simple read-evaluate-print-loop (REPL).

extern crate rlua;
extern crate rustyline;

use rlua::{Error, Lua, MultiValue};
use rustyline::Editor;

fn main() {
    let lua = Lua::new();
    let mut editor = Editor::<()>::new();

    loop {
        let mut prompt = "> ";
        let mut line = String::new();

        loop {
            match editor.readline(prompt) {
                Ok(input) => line.push_str(&input),
                Err(_) => return,
            }

            match lua.eval::<MultiValue>(&line, None) {
                Ok(values) => {
                    editor.add_history_entry(&line);
                    println!(
                        "{}",
                        values
                            .iter()
                            .map(|value| format!("{:?}", value))
                            .collect::<Vec<_>>()
                            .join("\t")
                    );
                    break;
                }
                Err(Error::SyntaxError {
                    incomplete_input: true,
                    ..
                }) => {
                    // continue reading input and append it to `line`
                    line.push_str("\n"); // separate input lines
                    prompt = ">> ";
                }
                Err(e) => {
                    eprintln!("error: {}", e);
                    break;
                }
            }
        }
    }
}