add loop examples

This commit is contained in:
Matthieu Jolimaitre 2024-10-24 07:03:35 +02:00
parent 6350e4a40f
commit dbeec4ee76
5 changed files with 110 additions and 49 deletions

View file

@ -0,0 +1,4 @@
let msg = "hello world";
msg

22
example/data/loops.mc Normal file
View file

@ -0,0 +1,22 @@
let i = 0;
loop {
i = i + 1;
print("i", i);
if (i > 5) break;
}
fn for(array, op) {
let index = 0;
loop {
let item = array[index];
if (item == none) break;
op(item, index);
index = index + 1;
}
}
for([1, 2, 3], (item, index) => {
print("at index", index, "item", item);
});

View file

@ -1,15 +1,21 @@
use std::{env::args, fs};
use microlang::Context;
use microlang::{Context, Value};
pub fn main() {
unsafe { backtrace_on_stack_overflow::enable() };
let mut context = Context::empty();
let lines = fs::read_to_string(args().nth(1).expect("Pass a file as arg 1.")).expect("File could not be read.");
for line in lines.lines() {
match context.eval(line.into()) {
Err(err) => panic!("Failed : {err:?}"),
Ok((_, value)) => println!("{}", value.serialize()),
context.define_built("print", |values, _| {
for val in values {
print!("{} ", val.serialize());
}
println!();
Ok(Value::None)
});
let lines = fs::read_to_string(args().nth(1).expect("Pass a file as arg 1.")).expect("File could not be read.");
match context.eval(lines) {
Err(err) => panic!("Failed : {err:?}"),
Ok((_, value)) => println!("{}", value.serialize()),
}
}