17个不稳定版本 (8个破坏性更新)
0.9.0 | 2023年11月28日 |
---|---|
0.7.2 | 2023年2月17日 |
#2 in #lox
135KB
3K SLoC
rulox
rulox
是一个嵌入Rust的轻量级脚本语言。它基于来自 Crafting Interpreters 的 Lox 语言。
基本用法
在你想使用rulox的每个模块的最顶层添加 use rulox::prelude::*
,然后使用你的Lox代码调用 lox
宏。注意,由于技术限制,当前的 lox
宏只能在返回 Result<_, LoxError>
的函数中使用。
示例
use rulox::prelude::*;
use rulox::LoxError;
fn main() -> Result<(), LoxError> {
lox! {
var a = 5;
print a + 2;
}
let b: f64 = a.get()?.try_into().unwrap();
println!("{}", b);
Ok(())
}
lox! {
for (var i = 5; i > 0; i = i - 1) print i;
}
lox! {
fun hello(name) {
print "Hello " + name + "! :)";
}
fun add_one(num) {
return num + 1;
}
}
hello.get()?.call([LoxValue::from("Alice")].into());
assert_eq!(add_one.get()?.call([LoxValue::from(3)].into())?, 4);
lox! {
var people = ["Bob", "Alice", "John"];
for (person in people) {
print "Hello " + person + "!";
}
}
lox! {
class Person {
init(name) {
this.name = name;
}
say_hello() {
print "Hello, my name is " + this.name + "!";
}
}
var jane = Person("Jane");
jane.say_hello();
}
lox! {
class Person {
init(name) {
this.name = name;
}
say_hello() {
print "Hello, my name is " + this.name + "!";
}
}
class Telepath > Person {
init(name, power) {
super(name);
this.power = power;
}
lift(weight) {
if (this.power < weight) {
print "It's too heavy!";
} else if (this.power == weight) {
print "I can't keep this up for long!";
} else {
print "This is child's play.";
}
}
}
var bob = Person("Bob");
bob.say_hello();
print "";
var alice = Telepath("Alice", 4);
alice.say_hello();
alice.lift(1.5);
alice.lift(4);
alice.lift(10);
}
lox! {
var except_ran = false;
var else_ran = false;
var finally_ran = false;
try {
print "try";
throw 1;
} except {
print "except";
except_ran = true;
} else {
print "else";
else_ran = true;
} finally {
print "finally";
finally_ran = true;
}
}
特性
- 变量声明
- 打印语句
- 控制流语句
- 循环
-
for ... in ...
循环 - 无限循环和
break
- 函数作为一等对象
- 面向对象
- 闭包
- 错误处理
- Async/await
- 哈希表
可能未来的特性
- 宏
依赖
~0.5–1.1MB
~24K SLoC