Menu
CoddyTech

הסבת מערכת מלאי ל-Luau

שיעור 28 מתוך 29 בקורס Lua למפתחי Luau של Coddy.

challenge icon

אתגר

בינוני

המירו את תוכנית הייחוס ב-Luau למודולים ב-Lua 5.1. כל שורת קלט היא שם באותיות ASCII קטנות, נקודתיים והפרש שלם עם סימן. צברו לפי שם, השאירו רק סכומים סופיים חיוביים, מיינו את השמות בסדר עולה והחזירו רשומות name=total המחוברות בפסיקים. החזירו empty אם לא נותרו רשומות. ממשו את inventory.aggregate(lines) בקובץ inventory.lua; app מעצב את התוצאה. כל שורות הקלט תקינות.

מימוש הייחוס ב-Luau

local lines: {string} = {"pen:3", "book:2", "pen:-1"} -- INPUT
local function aggregate(rows: {string}): {[string]: number}
  local counts: {[string]: number} = {}
  for _, row in rows do
    local name, amount = row:match("^([a-z]+):(%-?%d+)$")
    assert(name and amount, "expected name:delta")
    local delta = tonumber(amount)
    assert(delta, "expected numeric delta")
    counts[name] = (counts[name] or 0) + delta
  end
  return counts
end
local function run(rows: {string}): string
  local counts = aggregate(rows)
  local names: {string} = {}
  for name, count in counts do
    if count <= 0 then continue end
    table.insert(names, name)
  end
  table.sort(names)
  local out: {string} = {}
  for _, name in names do table.insert(out, `{name}={counts[name]}`) end
  return if #out == 0 then "empty" else table.concat(out, ",")
end
print(run(lines))

ערכו את app.lua, inventory.lua. הקובץ הנעול הגלוי main.lua קורא את stdin לרצף של שורות, קורא ל-app.run(lines) ומדפיס את הערך שהפונקציה מחזירה, עם תו newline אחד בסוף. אל תדפיסו הודעות אבחון ואל תשנו את שמות המודולים. קלט ריק יוצר רצף ריק. כל הערכים המספריים קטנים מספיק כדי למנוע גלישה.

בדיקות API ציבורי: inventory.aggregate(lines) מחזירה טבלה חדשה של הפרשים חתומים שסוכמו, ומשאירה גם סכומים שערכם אפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון נעשים ב-app. מנהל ההתקן הנעול בודק את ההתנהגות הזו לפני הקריאה ל-app.run. אם הבדיקות עוברות, הן אינן מדפיסות דבר.

מימוש הייחוס המלא ב-Luau רץ על טבלת lines לדוגמה. החליפו את השורה הראשונה כדי לנסות קלטים אחרים. מנהל ההתקן של שפת היעד מספק את אותם נתונים דרך stdin. שמרו על ההתנהגות תוך החלפת תחביר Luau ושמירה על ממשק המודול הנדרש.

נסו בעצמכם

-- בדיקות של ה-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))

כל השיעורים ביחידה Lua למפתחי Luau

תרגלו בעצמכם: קומפיילר Lua אונליין