Menu
CoddyTech

可读对象

Coddy 面向 Rust 开发者的 Lua 课程的第 37 课,共 48 课。

Rust 的 Display 实现控制普通格式化输出,而 Debug 是一种独立的表示约定。Lua 在对象的元表上使用 __tostring。普通的 tostring 字段不会激活这个钩子。返回所需的字符串,不要更改对象,并将格式化与相等性和键行为分开处理。

Rust 2021

Rust 声明:

struct Item{name:&'static str}
impl std::fmt::Display for Item{fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{write!(f,"Item:{}",self.name)}}

Rust 入口点:

fn main() {
println!("{}",Item{name:"pen"});
}

Lua 5.1

local Item={__tostring=function(self) return "Item:" .. self.name end}
print(setmetatable({name="pen"},Item))

移植时的陷阱

将 __tostring 安装在关联的元表上,而不是作为普通的实例字段。

challenge icon

挑战

简单

实现 Model.new(name, count) 和 Model.__tostring,使其返回 name[count]。输入分两行,分别是 name 和非负整数 count。应用会返回 tostring(instance)。

编辑 app.lua 和 model.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并打印其返回值,末尾加一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。

公共 API 检查:字符串转换会返回 name[count],包括 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))
quiz icon自我测试

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

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

自己练习: Lua 在线编译器