feat: 新增内置函数input

This commit is contained in:
0264408
2026-02-06 11:46:27 +08:00
parent f86300f3ce
commit 5c5ca8600a
3 changed files with 20 additions and 2 deletions

2
examples/input.ast Normal file
View File

@@ -0,0 +1,2 @@
let name = input("Your name: ");
print("Hello, " + name)

View File

@@ -11,10 +11,15 @@ pub struct Interpreter {
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())