Menu
CoddyTech

从 import 到 require

Coddy 面向 Lua 开发者的 Luau 课程的第 18 课,共 35 课。

Lua 5.1 的 require 通常使用 package.searchers 或 package.loaders 以及模块名称。此 Luau CLI 使用相对文件请求;请勿移植包配置或期望不受限制的文件 IO。Coddy 会单独添加 stdin API。

Lua 5.1 比较

local first=require("math")
local again=require("math")
print(first == again)

Luau 行为

CLI 使用相对路径加载本地模块,例如 require("./policy")。模块会返回其公开值。require 同一个解析后的模块会复用其结果。像 math 这样的内置库已经是全局变量,而不是通过 require("math") 加载的 CLI 文件。模块解析是宿主提供的功能。

local first=require("./sample")
local again=require("./sample")
print(first == again)

预期的 Luau 输出:

true

同级模块 sample.luau 包含:

return {value=7}
challenge icon

挑战

简单

输入为整数价格和非负数量。在 pricing.luau 中实现 subtotal 并从 app.luau 中调用它。返回乘积。请勿在 require 过程中进行打印。

编辑 app.luau、pricing.luau。可见且锁定的 main.luau 会将 stdin 读取为行序列,调用 app.run(lines),并打印其返回值(末尾带有一个换行符)。请勿打印诊断信息或修改模块名称。空输入会生成空序列。所有数值输入都足够小,不会发生溢出。

公共 API 检查:pricing.subtotal(price, quantity) 必须能独立于 app.run 工作,包括数量为零和带符号的价格。锁定的驱动程序会在调用 app.run 之前检查此行为。成功时,这些检查不会打印任何内容。

亲手试试

-- 公共 API 检查
do
local pricing=require("./pricing")
assert(pricing.subtotal(4,3)==12 and pricing.subtotal(4,0)==0 and pricing.subtotal(-2,3)==-6,"pricing.subtotal must implement the public product API")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Lua 开发者的 Luau中的所有课

自己练习: Luau 在线编译器