Menu
CoddyTech

Lua 인벤토리 포팅하기

Coddy의 Lua 개발자를 위한 Luau 코스 레슨. 35개 중 34번째.

challenge icon

챌린지

중급

레퍼런스 Lua 프로그램을 Luau 모듈로 포팅하세요. 각 입력 줄은 소문자 ASCII 이름, 콜론, 부호가 있는 정수 증감값(delta)으로 이루어져 있습니다. 이름별로 집계하고, 최종 합계가 양수인 항목만 유지하며, 이름을 오름차순으로 정렬한 뒤 쉼표로 연결된 name=total 항목을 반환하세요. 남은 항목이 없으면 empty를 반환하세요. inventory.luau에 inventory.aggregate(lines)를 구현하고, 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)는 부호가 있는 증감값을 합산한 새로운 테이블을 반환하며, 0인 최종 합계도 유지합니다. 빈 입력은 빈 테이블을 반환합니다. 서식화 및 필터링은 app에서 이루어집니다. 잠긴 드라이버는 app.run을 호출하기 전에 이 동작을 검사합니다. 이 검사는 성공 시 아무것도 출력하지 않습니다.

직접 해보기

-- Public 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의 모든 레슨

직접 연습해 보세요: 온라인 Luau 컴파일러