전체 재고 가치 계산하기
Coddy Lua 여정의 기초 섹션에 포함된 레슨. 90개 중 80번째.
챌린지
쉬움이제 다음 인벤토리를 사용하세요(현재 인벤토리를 덮어써도 됩니다):
local inventory = {
{name = "Health Potion", price = 15, stock = 8},
{name = "Mana Potion", price = 12, stock = 5},
{name = "Strength Potion", price = 25, stock = 3},
{name = "Speed Potion", price = 18, stock = 2}
}
목표는 재고에 있는 모든 물약의 총 골드 가치를 구하는 것입니다.
다음 단계를 따라 해 보세요.
1. totalValue라는 변수를 만들고 0으로 설정하세요. 물약을 하나씩 살펴보면서 총합을 추적하는 데 사용합니다.
2. 숫자형 for 루프를 사용해 inventory 테이블의 각 항목을 살펴보세요. 각 물약의 price에 stock을 곱해 해당 물약의 가치를 구하세요. 그 값을 totalValue에 더하세요.
3. 루프가 끝난 다음, 다음과 같이 결과를 출력하세요.
Total inventory value: 291 gold문자열 연결(..)을 사용해 텍스트와 totalValue의 값을 합치세요.
이전 단계의 표시 루프를 제거하세요. 이 단계에서는 총합이 적힌 줄만 출력합니다.
직접 해보기
-- Create the initial inventory with health potion
inventory = {
{name = "Health Potion", price = 15, stock = 8}
}
-- Create mana potion
manaPotion = {name = "Mana Potion", price = 12, stock = 5}
-- Add mana potion to inventory
table.insert(inventory, manaPotion)
-- Display all potions in inventory
for i = 1, #inventory do
print(inventory[i].name .. ": " .. inventory[i].price .. " gold")
end기초의 모든 레슨
직접 연습해 보세요: 온라인 Lua 컴파일러