易读的对象
Coddy 面向 PHP 开发者的 Luau 课程的第 37 课,共 48 课。
PHP 的 __toString 用于控制对象转换为文本的方式。Luau 在附加的元表中使用 __tostring,两者的拼写和位置不同。普通的 tostring 字段不会触发此钩子。返回稳定的表示形式,不要修改状态。
PHP 对比
<?php
class Item {public function __construct(public string $name){} public function __toString():string{return "Item:".$this->name;}} echo new Item("pen"),"\n";
Luau 的行为
__tostring 应放在实例使用的元表上。它会生成可读文本,而不会更改对象。名为 tostring 的普通字段不会被自动调用。为了方便测试,请保持文本稳定,而不是暴露默认的表地址。
local Item={__tostring=function(self) return "Item:" .. self.name end}
print(setmetatable({name="pen"},Item))预期的 Luau 输出:
Item:pen挑战
简单实现 Model.new(name, count) 和 Model.__tostring,使其返回 name[count]。输入分两行,分别为名称和非负整数计数。应用会返回 tostring(instance)。
编辑 app.luau、model.luau。可见的锁定文件 main.luau 会将 stdin 读入一个行序列,调用 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))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 Luau中的所有课
自己练习: Luau 在线编译器