A complete Lua 5.4 interpreter written in MoonBit
moon build --target native --releasemoon run cmd/main -- script.lua arg1 arg2
moon run cmd/main -- -e 'print("hello")'
moon run cmd/main # 从 stdin 读取;终端下会显示提示符moon test$ moon run cmd/main -- -e 'local 名字 = "世界"; print("你好," .. 名字)'
你好,世界| 示例 | 展示了什么 |
|---|---|
| examples/basics.lua | 整数与浮点两种数字子类型、字节串、表、闭包、变长参数、尾调用、pcall/xpcall |
| examples/coroutines.lua | coroutine.wrap 生成器、在元方法中让出(yield)、coroutine.close 触发待处理的 <close> 变量 |
| examples/metatables.lua | 运算符重载、__index 表链、只读代理、to-be-closed 变量 |
moon run cmd/main -- examples/basics.luamoon run examples/embed| 包 | 内容 |
|---|---|
| hongweifei/lua(根包) | 嵌入用的公开接口:Lua 句柄、Value/Table 别名、ToLua、host_function、LuaError(embed.mbt、values.mbt、host_functions.mbt、errors.mbt) |
| src/host | 宿主边界:ffi.mbt 里的 extern "c" 声明,以及实现它们的 stub.c |
| src/core | 值模型与状态:value、objects、table、table_hash、thread、userdata、state;数字(number、number_format)、opcode、bytes、core 直接调用的宿主服务、names(错误消息从运行中的代码借用的名字)以及 binop / load_outcome |
| src/vm | 解释器循环及其派发:vm、vm_frame、vm_call、vm_instr、vm_index、vm_arith、vm_compare、vm_convert、vm_hook |
| src/compiler | 扫描器(token、lexer、lexer_string)、语法分析(ast、parser、parser_expr、parser_stat)与代码生成(funcstate、funcstate_regs、compiler_entry、compiler_expr、compiler_call、compiler_stat、compiler_scope) |
| src/chunk | string.dump(chunk_dump)以及加载其产物的 chunk_undump |
| src/pattern | Lua 模式匹配,以及建立在它之上的库函数 |
| src/load | 把源码或二进制 chunk 变成可调用的原型:state_load、base_load |
| src/lib/base、string、math、io、os、table、utf8、coroutine、debug | 每个标准库一个包 |
| src/lua | 对外入口:lua、api、stdlib、lib_package,以及 Lua 测试套件(*_test.mbt) |
| cmd/main | 命令行界面 |
| examples/embed | 嵌入解释器的示例程序;与它并列的 Lua 示例是数据文件,不是包 |
host
└ core ─┬─ vm
├─ compiler
├─ chunk
├─ pattern
├─ load ← chunk, compiler, vm
├─ lib/* ← load, vm, pattern, chunk
└─ lua ← lib/*, load, vm
└ (根包) ← core, lualet lua = Lua::new()
lua.set("上限", 100) // MoonBit 的值直接写进 globals
lua.set_function("平方", fn(args) { // MoonBit 闭包就是 Lua 函数
match args[0].as_integer() {
Some(x) => Ok([Value::VInt(x * x)])
None => Err(Value::text("integer expected"))
}
})
let total = lua.eval_int("return 平方(3) + 上限") // Ok(109)let size : Map[String, Int]? = read_lua(lua.get("配置")) // 表 → Map
let items : Array[Int64]? = read_lua(lua.get("清单")) // 表 → 序列
let limit : Result[Int64, LuaError] = lua.get_as("上限") // Err 里是语言那种话
let vs = lua.run("return '一', '二'").unwrap()
let words : Result[Array[String], LuaError] = lua.values_as(vs)moon testmoon run --target native tools/run_bench.mbtx /path/to/reference/luapub struct Lua {
// private fields
}test "calling a function a chunk defined" {
let lua = Lua::new()
let _ = lua.run("function double(x) return x * 2 end")
let vs = lua.call_global("double", args=[Value::VInt(21L)]).unwrap()
assert_eq(vs[0].as_integer(), Some(42L))
}test "a chunk's first result, typed" {
let lua = Lua::new()
let rows : Result[Array[Int64], LuaError] = lua.eval_as("return {1, 2, 3}")
assert_eq(rows.unwrap(), [1L, 2L, 3L])
let not_a_number : Result[Int64, LuaError] = lua.eval_as("return nil")
assert_eq(not_a_number.unwrap_err().message, "number expected, got nil")
// `{}` is an empty table, not a missing value.
let empty_table : Result[Int64, LuaError] = lua.eval_as("return {}")
assert_eq(empty_table.unwrap_err().message, "number expected, got table")
}test "reading a global as a MoonBit type" {
let lua = Lua::new()
let missing : Result[String, LuaError] = lua.get_as("非")
assert_true(missing is Err(_))
lua.set("问候", "你好")
let got : Result[String, LuaError] = lua.get_as("问候")
assert_eq(got.unwrap(), "你好")
}test "a MoonBit module a script can require" {
let lua = Lua::new()
lua.preload("配置", fn(args) {
let _ = args
let t = new_table()
t.set_str("上限", Value::VInt(42L))
Ok([t.as_value()])
})
assert_eq(lua.eval_int("return require('配置').上限").unwrap(), 42L)
}test "require from the host" {
let lua = Lua::new()
lua.preload("配置", fn(args) {
let _ = args
let t = new_table()
t.set_str("上限", Value::VInt(42L))
Ok([t.as_value()])
})
let m = lua.require("配置").unwrap()
assert_eq(m.type_name(), "table")
// The loader ran once: `require` caches, so the two handles are one table.
assert_true(m.raw_equal(lua.require("配置").unwrap()))
}test "a chunk's results" {
let lua = Lua::new()
let vs = lua.run("return 1 + 2, 'x'").unwrap()
assert_eq(vs[0].as_integer(), Some(3L))
assert_eq(vs[1].as_text(), Some("x"))
}test "reading one value" {
let lua = Lua::new()
let items : Result[Array[Int64], LuaError] = lua.value_as(
lua.eval("return {7, 8, 9}").unwrap(),
)
assert_eq(items.unwrap(), [7L, 8L, 9L])
let wrong : Result[Array[Int64], LuaError] = lua.value_as(
lua.eval("return {7, 'x'}").unwrap(),
)
// A failure inside a table names the *entry*, not the table that held it.
assert_eq(wrong.unwrap_err().message, "number expected, got string")
}test "a host closure called from Lua" {
let lua = Lua::new()
lua.set_function("长度", fn(args) {
match args[0].as_bytes() {
Some(b) => Ok([Value::VInt(b.length().to_int64())])
None => Err(Value::text("string expected"))
}
})
let vs = lua.run("return 长度('你好'), 长度('abc')").unwrap()
assert_eq(vs[0].as_integer(), Some(6L))
assert_eq(vs[1].as_integer(), Some(3L))
// An `Err` raises, so the script sees an ordinary Lua error it can catch.
let caught = lua.run("return select(2, pcall(长度, 1))").unwrap()
assert_true(caught[0].as_text().unwrap_or("").contains("string expected"))
}test "reading rules, in both directions" {
let lua = Lua::new()
// A string spelling a number reads as one, because `math.tointeger` does.
let from_text : Int64? = read_lua(lua.eval("return '42'").unwrap())
assert_eq(from_text, Some(42L))
// A number does not read as text, though Lua's `tostring` would make one.
let number_as_text : String? = read_lua(lua.eval("return 42").unwrap())
assert_eq(number_as_text, None)
assert_eq(lua.show(lua.eval("return 42").unwrap()), "42")
// An integer too wide for MoonBit's `Int` is nothing rather than a wrap.
let too_wide : Int? = read_lua(lua.eval("return math.maxinteger").unwrap())
assert_eq(too_wide, None)
let fits : Int? = read_lua(lua.eval("return 42").unwrap())
assert_eq(fits, Some(42))
// A `boolean` reads strictly; Lua's *truth* is `Lua::eval_bool`'s question.
let zero_as_bool : Bool? = read_lua(lua.eval("return 0").unwrap())
assert_eq(zero_as_bool, None)
assert_eq(lua.eval_bool("return 0").unwrap(), true)
// Compound types name themselves the same way.
let items : Array[Int64]? = read_lua(lua.eval("return {7, 8}").unwrap())
assert_eq(items, Some([7L, 8L]))
let cfg : Map[String, Int64]? = read_lua(
lua.eval("return {a = 1, b = 2}").unwrap(),
)
assert_eq(cfg, Some(Map([("a", 1L), ("b", 2L)])))
// A table is a sequence only up to its first absent field.
let holed : Array[Int64]? = read_lua(lua.eval("return {1, nil, 3}").unwrap())
assert_eq(holed, Some([1L]))
// A `nil` is `None`, and so is a wrong type -- `is_nil` tells them apart.
let maybe : Int64? = read_lua(lua.eval("return nil").unwrap())
assert_eq(maybe, None)
}