Luau 인벤토리 이식하기
Coddy의 Luau 개발자를 위한 Lua 코스 레슨. 29개 중 28번째.
챌린지
중급참고 Luau 프로그램을 Lua 5.1 모듈로 포팅하세요. 각 입력 줄은 소문자 ASCII 이름, 콜론, 부호가 있는 정수 증분으로 이루어집니다. 이름별로 합산하고, 최종 합계가 양수인 항목만 남긴 다음, 이름을 오름차순으로 정렬하고 name=total 항목을 쉼표로 연결해 반환하세요. 남은 항목이 없으면 empty를 반환하세요. inventory.lua에서 inventory.aggregate(lines)를 구현하고, 결과는 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는 표준 입력을 줄의 시퀀스로 읽고, app.run(lines)을 호출한 뒤 반환된 값을 마지막에 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 시퀀스가 됩니다. 모든 숫자 입력은 오버플로를 방지할 수 있을 만큼 작습니다.
공개 API 검사: inventory.aggregate(lines)는 부호가 있는 증분을 합산한 새 테이블을 반환하며, 합계가 0인 항목도 유지합니다. 입력이 비어 있으면 빈 테이블을 반환합니다. 형식화와 필터링은 app에서 수행합니다. 잠금된 드라이버는 app.run을 호출하기 전에 이 동작을 확인합니다. 이 검사들은 성공하면 아무것도 출력하지 않습니다.
완전한 Luau 참고 코드는 샘플 lines 테이블을 사용해 실행됩니다. 다른 입력을 시도하려면 첫 번째 줄을 바꾸세요. 대상 드라이버는 표준 입력에서 같은 데이터를 제공합니다. Luau 구문을 바꾸고 필요한 모듈 API를 유지하면서 동작을 보존하세요.
직접 해보기
-- 공개 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의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러