Menu
CoddyTech

对象的可读表示

Coddy 面向 Dart 开发者的 Luau 课程的第 37 课,共 48 课。

Dart 的 toString 提供文本表示形式,可用于打印和插值。Luau 会识别附加的元表中的 __tostring。名为 tostring 的普通字段不会启用此行为。返回稳定的文本,不要更改对象。

Dart 对比

class Item {@override String toString()=>"Item:pen";}
void main() {
print(Item());
}

Luau 的行为

__tostring 应放在实例使用的元表中。它会生成可读文本,而不会更改对象。系统不会自动查询名为 tostring 的普通字段。为了便于测试,请保持文本稳定,而不是暴露默认的表地址。

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

预期的 Luau 输出:

Item:pen
challenge icon

挑战

简单

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

编辑 app.luau、model.luau。可见但已锁定的 main.luau 会将标准输入读入一个行序列,调用 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))
quiz icon自我测试

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

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

自己练习: Luau 在线编译器