feat: 新增内置函数input
This commit is contained in:
2
examples/input.ast
Normal file
2
examples/input.ast
Normal file
@@ -0,0 +1,2 @@
|
||||
let name = input("Your name: ");
|
||||
print("Hello, " + name)
|
||||
@@ -12,9 +12,14 @@ impl Interpreter {
|
||||
pub fn new() -> Self {
|
||||
let env = Rc::new(RefCell::new(Env::new(None)));
|
||||
|
||||
let mut env_mut = env.borrow_mut();
|
||||
|
||||
// 注册内置函数
|
||||
env.borrow_mut().define("print".to_string(), Value::NativeFunction(native_print));
|
||||
env.borrow_mut().define("clock".to_string(), Value::NativeFunction(native_clock));
|
||||
env_mut.define("print".to_string(), Value::NativeFunction(native_print));
|
||||
env_mut.define("input".to_string(), Value::NativeFunction(native_input));
|
||||
env_mut.define("clock".to_string(), Value::NativeFunction(native_clock));
|
||||
|
||||
drop(env_mut);
|
||||
|
||||
Self { env }
|
||||
}
|
||||
@@ -283,6 +288,17 @@ fn native_print(args: Vec<Value>) -> Value {
|
||||
Value::Nil
|
||||
}
|
||||
|
||||
fn native_input(args: Vec<Value>) -> Value {
|
||||
if let Some(prompt) = args.get(0) {
|
||||
print!("{}", prompt);
|
||||
use std::io::Write;
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
let mut buffer = String::new();
|
||||
std::io::stdin().read_line(&mut buffer).unwrap();
|
||||
Value::String(buffer.trim_end().to_string())
|
||||
}
|
||||
|
||||
// 获取当前时间
|
||||
fn native_clock(_args: Vec<Value>) -> Value {
|
||||
Value::Number(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs_f64())
|
||||
|
||||
Reference in New Issue
Block a user