הסבת אינוונטר של Lua
שיעור 34 מתוך 35 בקורס Luau למפתחי Lua של Coddy.
אתגר
בינוניהסב את תוכנית הייחוס ב-Lua למודולי Luau. כל שורת קלט מורכבת משם באותיות ASCII קטנות, נקודתיים, ודלתא של מספר שלם בעל סימן. קבץ לפי שם, שמור רק סכומים סופיים חיוביים, מיין שמות בסדר עולה והחזר רשומות name=total מופרדות בפסיקים. החזר empty כאשר לא נותר דבר. ממש את inventory.aggregate(lines) ב-inventory.luau; המודול app מעצב את התוצאה. כל שורות הקלט מעוצבות כהלכה.
ייחוס Lua 5.1
-- Lua 5.1 reference with explicit module registration.
package.preload["app"]=function()
local M = {}
function M.run(lines)
local inventory=require("inventory")
local counts=inventory.aggregate(lines)
local names={}
for name,n in pairs(counts) do if n>0 then names[#names+1]=name end end
table.sort(names)
local out={}
for _,name in ipairs(names) do out[#out+1]=name .. "=" .. counts[name] end
return #out>0 and table.concat(out,",") or "empty"
end
return M
end
package.preload["inventory"]=function()
local M={}
function M.aggregate(lines)
local counts={}
for _,s in ipairs(lines) do
local name,n=s:match("^([a-z]+):(%-?%d+)$")
counts[name]=(counts[name] or 0)+tonumber(n)
end
return counts
end
return M
end
-- Public API checks
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))ערוך את app.luau, inventory.luau. הקובץ הנעול והגלוי main.luau קורא את ה-stdin לרצף של שורות, קורא ל-app.run(lines), ומדפיס את הערך המוחזר שלו עם תו ירידת שורה אחד בסוף. אין להדפיס פלטי אבחון או לשנות את שמות המודולים. קלט ריק מחזיר רצף ריק. כל הקלטים הנומריים קטנים מספיק כדי למנוע גלישה.
בדיקות API ציבורי: הפונקציה inventory.aggregate(lines) מחזירה טבלה חדשה של סכומי דלתאות בעלי סימן, תוך שמירה על סכומים השווים לאפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון מתבצעים ב-app. קוד ההרצה (driver) הנעול בודק התנהגות זו לפני הקריאה ל-app.run. בדיקות אלו אינן מדפיסות דבר כאשר הן מצליחות.
נסו בעצמכם
-- בדיקות API ציבורי
do
local inventory=require("./inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
כל השיעורים ביחידה Luau למפתחי Lua
תרגלו בעצמכם: קומפיילר Luau אונליין