移植 Ruby 房间对象
Coddy 面向 Ruby 开发者的 Lua 课程的第 48 课,共 48 课。
挑战
中等将这个完整的 Ruby 程序移植为 Lua 模块。第一行是非负的房间容量,其余各行是带符号的整数预订请求。只接受严格大于零且符合容量限制的请求。请求失败时,已使用的座位数必须保持不变。返回 remaining:accepted。Model.new(capacity) 会公开 capacity 和 used,后者初始值为零;Model:reserve(seats) 返回布尔值,并且只在成功时修改状态。不同房间必须互相独立。将 Ruby 的实例变量不变量转换为显式的 Lua 表状态。
Ruby 房间参考代码
class Room
attr_reader :capacity, :used
def initialize(capacity)
@capacity = capacity
@used = 0
end
def reserve(seats)
return false if seats <= 0 || @used + seats > @capacity
@used += seats
true
end
end
lines = STDIN.read.lines.map(&:chomp)
room = Room.new(Integer(lines.shift, 10))
accepted = lines.count { |line| room.reserve(Integer(line, 10)) }
puts "#{room.capacity - room.used}:#{accepted}"编辑 app.lua 和 model.lua。可见的锁定文件 main.lua 会将标准输入读入各行,检查公共 API,调用 app.run(lines),并输出一个返回值,末尾带换行符。不要打印诊断信息。房间任务的输入不为空;库存输入可能为空。
亲手试试
-- 公共 API 检查
do
local Model=require("model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
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 在线编译器