从继承到查找链
Coddy 面向 Ruby 开发者的 Lua 课程的第 39 课,共 48 课。
Ruby 类继承会自动查找方法,并支持 super。Lua 对象模式通过 __index 显式构造查找链。实例可以回退到子类方法表,而子类方法表又可以回退到基类表。查找不到时,不会将字段复制到实例中。若要调用被重写的基类行为,请指定基类函数,并显式传入当前接收者。Lua 没有内置的 Ruby super 关键字。
Ruby
class Base
def value; 3; end
end
class Child < Base
end
puts Child.new.valueLua 5.1
local Base={}
function Base:value() return 3 end
local Child=setmetatable({}, {__index=Base})
Child.__index=Child
local c=setmetatable({},Child)
print(c:value())
移植时的陷阱
不要以为所有元方法都会通过普通的 __index 链继承。特殊操作的查找有其自身的元表规则。
在可编辑的 Lua 模块中实现所需的公共 API。可见但锁定的 main.lua 会通过 require 加载这些模块,提供输入和输出,并检查指定的模块行为。请保留模块名称和返回约定。
挑战
简单Base 保存单价,并提供 total(quantity)。Model 是一个子原型,它会重写 total,只添加一次固定费用,即使数量为零也是如此。输入依次为价格、数量、费用。返回 price*quantity+fee。将 Base 保留在 base.lua 中。
编辑 app.lua、base.lua、model.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并在末尾添加一个换行符后打印其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数字输入都足够小,不会溢出。
公共 API 检查:Base.total(receiver, quantity) 会将 receiver.price 乘以 quantity。Model.new(price, fee) 会返回相互独立的对象,这些对象的 total 会添加一次费用,即使数量为零也是如此。只检查可观察到的 API 行为。锁定的驱动程序会在调用 app.run 前检查这些行为。检查成功时不会打印任何内容。
亲手试试
-- 公共 API 检查
do
local Base=require("base")
local Model=require("model")
assert(Base.total({price=4},3)==12,"base total multiplies receiver price by quantity")
local a,b=Model.new(3,2),Model.new(5,1)
assert(a:total(4)==14 and a:total(0)==2,"child total adds the flat fee once")
assert(b:total(2)==11 and a:total(1)==5,"instances retain independent price and fee")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 Lua中的所有课
自己练习: Lua 在线编译器