移植 Luau 房间对象
Coddy 面向 Luau 开发者的 Lua 课程的第 29 课,共 29 课。
挑战
中等将 Luau 参考实现移植到 Lua 5.1 模块中。第一行输入是非负的房间容量,其余各行是带符号的整数预订请求。只接受严格大于零且符合容量限制的请求。失败的请求不会改变已使用座位数。返回 remaining:accepted。在 model.lua 中实现 Model.new(capacity) 和 Model:reserve(seats);reserve 返回布尔值。每次运行都使用一个新对象。
Luau 参考实现
local lines: {string} = {"5", "2", "3"} -- INPUT
type RoomState = {capacity: number, used: number}
local Room = {}
Room.__index = Room
function Room.new(capacity: number)
return setmetatable({capacity=capacity, used=0}, Room)
end
function Room.reserve(self: RoomState, seats: number): boolean
if seats <= 0 or self.used + seats > self.capacity then return false end
self.used += seats
return true
end
local function run(rows: {string}): string
local capacity = tonumber(rows[1])
assert(capacity, "expected capacity")
local room = Room.new(capacity)
local accepted = 0
for i=2,#rows do
local seats = tonumber(rows[i])
assert(seats, "expected seats")
if room:reserve(seats) then accepted += 1 end
end
return `{room.capacity-room.used}:{accepted}`
end
print(run(lines))编辑 app.lua、model.lua。可见的锁定文件 main.lua 会将标准输入读入一个行序列,调用 app.run(lines),并在返回值后打印一个换行符。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。
公共 API 检查:Model.new(capacity) 会公开 capacity 和 used,且 used 初始为零。reserve 返回布尔值,并且只会在请求为正数且符合容量限制时更新 used。各个房间相互独立。锁定的驱动程序会在调用 app.run 前检查这些行为。检查成功时不会打印任何内容。
完整的 Luau 参考实现会使用示例 lines 表运行。替换第一行即可尝试其他输入。目标驱动程序会从标准输入提供相同的数据。替换 Luau 语法并保留所需的模块 API,同时保持行为不变。
亲手试试
-- 公共 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))
面向 Luau 开发者的 Lua中的所有课
自己练习: Lua 在线编译器