从导入语句到 require
Coddy 面向 Python 开发者的 Lua 课程的第 29 课,共 48 课。
Lua 模块是一段会返回 API 值(通常是一个表)的代码块。require("pricing") 会在模块路径中查找 pricing.lua,并将返回的值缓存在 package.loaded 中。导入模块时不应打印内容。
Python
import math
import math as again
print(math is again)Lua
local first=require("math")
local again=require("math")
print(first == again)移植时的陷阱
在 require 中使用以点分隔的模块名称,不要使用文件扩展名。除非导出到返回的表中,否则局部声明会保持私有。本课程会将所有模块放在锁定的主文件旁边。
挑战
简单输入是整数价格和非负数量。在 pricing.lua 中实现 subtotal,并从 app.lua 调用它。返回乘积。不要在 require 期间打印内容。
编辑 app.lua、pricing.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Lua中的所有课
自己练习: Lua 在线编译器