Lua 룸 오브젝트 포팅하기
Coddy의 Lua 개발자를 위한 Luau 코스 레슨. 35개 중 35번째.
챌린지
중급Lua 레퍼런스를 포팅하세요. 첫 번째 입력 줄은 음수가 아닌 방 수용 인원이며, 나머지 줄은 부호가 있는 정수 예약 요청입니다. 수용 가능한 양수 요청만 승인하세요. 실패한 요청은 사용된 좌석 수(used)를 변경하지 않습니다. remaining:accepted를 반환하세요. model.luau에 Model.new(capacity) 및 Model:reserve(seats)를 구현하세요. reserve는 불리언(boolean)을 반환합니다. 실행마다 새로운 객체를 사용하세요.
Lua 5.1 레퍼런스
-- Lua 5.1 reference with explicit module registration.
package.preload["app"]=function()
local M = {}
function M.run(lines)
local Model=require("model")
local room=Model.new(tonumber(lines[1]))
local accepted=0
for i=2,#lines do if room:reserve(tonumber(lines[i])) then accepted=accepted+1 end end
return (room.capacity-room.used) .. ":" .. accepted
end
return M
end
package.preload["model"]=function()
local Model={}
Model.__index=Model
function Model.new(capacity) return setmetatable({capacity=capacity,used=0},Model) end
function Model:reserve(seats)
if seats<=0 or self.used+seats>self.capacity then return false end
self.used=self.used+seats;return true
end
return Model
end
-- Public API checks
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))app.luau, model.luau를 수정하세요. 잠겨 있는 main.luau는 표준 입력(stdin)을 줄 시퀀스로 읽고, app.run(lines)를 호출한 뒤 반환된 값을 마지막 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 빈 입력은 빈 시퀀스를 생성합니다. 모든 수치 입력은 오버플로를 방지할 수 있을 만큼 충분히 작습니다.
공개 API 검사: Model.new(capacity)는 capacity 및 used를 노출하며, used의 초기값은 0입니다. reserve는 불리언을 반환하며 수용 가능한 양수 요청에 대해서만 used를 업데이트합니다. 각 방은 독립적입니다. 잠긴 드라이버는 app.run을 호출하기 전에 이 동작을 검사합니다. 이 검사들은 성공 시 아무것도 출력하지 않습니다.
직접 해보기
-- Public 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))
Lua 개발자를 위한 Luau의 모든 레슨
직접 연습해 보세요: 온라인 Luau 컴파일러