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)، ثم يطبع القيمة التي أعادها مع سطر جديد أخير. لا تطبع رسائل تشخيصية ولا تغيّر أسماء الوحدات. ينتج عن الإدخال الفارغ تسلسل فارغ. جميع القيم العددية صغيرة بما يكفي لتجنّب تجاوز السعة.

فحوصات الواجهة البرمجية العامة: تعيد inventory.aggregate(lines) جدولًا جديدًا للمجاميع الموقّعة، مع الاحتفاظ بالمجاميع التي تساوي صفرًا. ينتج عن الإدخال الفارغ جدول فارغ. تتم التصفية والتنسيق في app. يتحقق المشغّل المقفَل من هذا السلوك قبل استدعاء app.run. لا تطبع هذه الفحوصات أي شيء عند نجاحها.

يعمل مرجع Luau الكامل على جدول lines النموذجي. استبدل ذلك السطر الأول لتجربة مدخلات أخرى. يمرّر المشغّل المستهدف البيانات نفسها عبر stdin. حافظ على السلوك مع استبدال صياغة Luau والإبقاء على واجهة الوحدة المطلوبة.

جرّب بنفسك

-- فحوصات واجهة برمجة التطبيقات العامة
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 عبر الإنترنت