值相等元方法
Coddy 面向 Dart 开发者的 Luau 课程的第 41 课,共 48 课。
Dart 自定义值相等性在用于哈希集合时,需要兼容的 hashCode。Luau 的共享 __eq 行为必须显式安装,而表值键仍使用原始身份比较。结构注解不会自动生成相等性、哈希或不可变性。
Dart 对比
class Point {final int x,y; Point(this.x,this.y);
@override bool operator ==(Object other)=>other is Point && x==other.x && y==other.y;
@override int get hashCode=>Object.hash(x,y);}
void main() {
final a=Point(1,2), b=Point(1,2); print(a==b);
}
Luau 的行为
值相等性需要经过精心设计的运行时机制。这些任务使用共享的相等元方法,并比较相关字段。仅有结构类型并不会提供相等性、哈希或不可变性。冻结和克隆是独立的选择,且都是浅层操作。
local Point={__eq=function(a,b) return a.x==b.x and a.y==b.y end}
local a=setmetatable({x=1,y=2},Point)
local b=setmetatable({x=1,y=2},Point)
print(a==b)预期的 Luau 输出:
true挑战
简单使用 Model.new(x,y) 和 Model.__eq 实现点对象。输入包含 4 行整数,分别表示 x1、y1、x2、y2。应用会使用 a == b,并返回 equal 或 different。
编辑 app.luau、model.luau。可见的锁定文件 main.luau 会将标准输入读入一个行序列,调用 app.run(lines),并在末尾添加一个换行符来打印返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都很小,不会造成溢出。
公开 API 检查:点相等比较必须是对称的,同时比较 x 和 y,并能区分任一坐标的变化。锁定的驱动程序会在调用 app.run 前检查此行为。这些检查成功时不会打印任何内容。
亲手试试
-- 公开 API 检查
do
local Model=require("./model")
local a,b,c=Model.new(1,2),Model.new(1,2),Model.new(1,3)
assert(a==b and b==a and a~=c and c~=a,"point equality compares both coordinates symmetrically")
local d=Model.new(2,2)
assert(a~=d,"x also participates in equality")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Dart 开发者的 Luau中的所有课
自己练习: Luau 在线编译器