示例
四个短程序。每一个都是一个完整的文件 —— 把它拷进 hello.lomt 再运行。
每个下面你看到的,是它实际打印出来的东西。
最小的程序
_start 是机器开始的地方,输出走 write 系统调用:文件描述符、
指针、长度。第二次调用是 exit。
module hello fn _start() { let s: str = "hello from Loment\n"; syscall4(1, 1, str_ptr(s) as u64, str_len(s) as u64); syscall4(60, 0, 0, 0);}
hello from Loment
一个带返回值的函数
类型写出来,从不推断;没有隐式的数值转换,所以一个需要换成别的宽度的整数,会用
as 把这件事说出来。
module funct fn write_str(fd: u64, s: str) -> i64 { return syscall4(1, fd, str_ptr(s) as u64, str_len(s) as u64);} fn larger(a: u32, b: u32) -> u32 { if a > b { return a; } return b;} fn _start() { let m: u32 = larger(7, 9); if m == 9 { write_str(1, "larger(7, 9) came back with 9\n"); syscall4(60, 0, 0, 0); } write_str(1, "unexpected\n"); syscall4(60, 1, 0, 0);}
larger(7, 9) came back with 9
一个常量和一个循环
for 走一个区间并绑定下标。const 是一个编译期值,可用作边界。
module counting const LIMIT: u32 = 5; fn write_str(fd: u64, s: str) -> i64 { return syscall4(1, fd, str_ptr(s) as u64, str_len(s) as u64);} fn _start() { let sum: u32 = 0; for i in 0..LIMIT { sum = sum + i; } if sum == 10 { write_str(1, "the loop summed 0 through 4\n"); syscall4(60, 0, 0, 0); } write_str(1, "unexpected\n"); syscall4(60, 1, 0, 0);}
the loop summed 0 through 4
一个数组,以切片传入
[u32; 3] 是一个把长度写进类型里的数组;[u32] 是一个切片,
它自身不携带长度。&xs 把数组当作切片交出去,slice_len
问它有多长。
module slice fn write_str(fd: u64, s: str) -> i64 { return syscall4(1, fd, str_ptr(s) as u64, str_len(s) as u64);} fn sum(xs: [u32]) -> u32 { let acc: u32 = 0; let i: u32 = 0; while i < slice_len(xs) { acc = acc + xs[i]; i = i + 1; } return acc;} fn _start() { let xs: [u32; 3] = [1, 2, 3]; let s: u32 = sum(&xs); if s == 6 { write_str(1, "the slice summed to 6\n"); syscall4(60, 0, 0, 0); } write_str(1, "unexpected\n"); syscall4(60, 1, 0, 0);}
the slice summed to 6
更多
仓库在 loment/examples/ 下带了一个更大的集合。它们并非全都在这个发布里能链接。
这一页上的所有东西都是用已发布的 0.1.4 包编译并运行的。能力系统 ——
首页给了一个例子的那个 —— 不在这四个之中,因为它在这个发布里
链接不过。那是自举链接器里一个已知的缺陷,不是语言的问题:参考实现能链接同一个程序并运行
它。同一类失败见
issue #102 和
#38。