定制字符串转换
Coddy 面向 Go 开发者的 Lua 课程的第 37 课,共 48 课。
Go 的 fmt 会识别 Stringer 接口的 String 方法,用于生成易读的格式。Lua 则使用对象元表上的 __tostring。普通的 tostring 字段不会自动成为转换钩子。返回所需的字符串,不要更改状态,并将易读的表示形式与对象相等性分开处理。
Go
package main
import ("fmt")
type Item struct {Name string}
func(i Item) String()string{return "Item:"+i.Name}
func main(){
fmt.Println(Item{Name:"pen"})
}
Lua
local Item = {}
function Item.__tostring(self)
return self.name .. "[" .. self.count .. "]"
end
local item = setmetatable({name = "pen", count = 3}, Item)
print(item)移植时的陷阱
在元表上设置 __tostring,并返回一个字符串。
挑战
简单实现 Model.new(name, count) 和 Model.__tostring,使其返回 name[count]。输入分两行,分别为 name 和非负整数 count。应用会返回 tostring(instance)。
编辑 app.lua 和 model.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并在末尾添加一个换行符后打印其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到空序列。所有数字输入都足够小,不会溢出。
公共 API 检查:字符串转换会返回 name[count],包括计数为零的情况;多个实例之间互不影响,重复调用也能得到相同结果。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。
亲手试试
-- 公开 API 检查
do
local Model=require("model")
local a,b=Model.new("pen",3),Model.new("book",0)
assert(tostring(a)=="pen[3]" and tostring(b)=="book[0]","object text must reflect its own name and count")
assert(tostring(a)=="pen[3]","formatting must be repeatable")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 Lua中的所有课
自己练习: Lua 在线编译器