הסבת אובייקטים של חדר ל-Luau
שיעור 29 מתוך 29 בקורס Lua למפתחי Luau של Coddy.
אתגר
בינוניהמירו את מימוש הייחוס ב-Luau למודולים ב-Lua 5.1. שורת הקלט הראשונה היא קיבולת החדר, מספר שלם שאינו שלילי; השורות הנותרות הן בקשות להזמנה, מספרים שלמים עם סימן. קבלו רק בקשות חיוביות ממש שמתאימות לקיבולת. בקשות שנדחות אינן משנות את מספר המושבים שנעשה בהם שימוש. החזירו remaining:accepted. ממשו את Model.new(capacity) ואת Model:reserve(seats) בקובץ model.lua; הפעולה 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 קורא את stdin לרצף של שורות, קורא ל-app.run(lines) ומדפיס את הערך שהפונקציה מחזירה, עם תו שורה חדשה אחד בסוף. אל תדפיסו הודעות אבחון ואל תשנו את שמות המודולים. קלט ריק יוצר רצף ריק. כל הקלטים המספריים קטנים מספיק כדי למנוע גלישה.
בדיקות API ציבוריות: Model.new(capacity) חושפת את capacity ואת used, שערכו ההתחלתי הוא אפס. הפעולה reserve מחזירה ערך בוליאני ומעדכנת את used רק עבור בקשה חיובית שמתאימה לקיבולת. החדרים אינם תלויים זה בזה. מנהל ההרצה הנעול בודק את ההתנהגות הזאת לפני קריאה ל-app.run. הבדיקות האלה אינן מדפיסות דבר כשהן מצליחות.
מימוש הייחוס המלא ב-Luau רץ עם טבלת lines לדוגמה. החליפו את השורה הראשונה כדי לנסות קלטים אחרים. מנהל ההרצה של שפת היעד מספק את אותם נתונים דרך stdin. שמרו על ההתנהגות תוך החלפת התחביר של 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))
כל השיעורים ביחידה Lua למפתחי Luau
תרגלו בעצמכם: קומפיילר Lua אונליין