解答物品查询
本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 73 课,共 80 课。
挑战
中等回答询问某件物品的玩家。
- 删除
-- Try it下方的代码行。 - 在它下方读取
local category = io.read()和local id: number = tonumber(io.read()) or 0。 - 对于
"weapon",对findItem(weapons, id)的结果打印describeWeapon(item);否则使用potions和describePotion。 - 当
findItem返回nil时,打印Item not found。
按“运行”:输入 weapon 和 2 后,你会看到 Weapon: Fire Axe (damage 40)。
亲手试试
-- 所有库存共用的物品结构
type Item<T> = {
id: number,
name: string,
data: T,
}
local sword: Item<{damage: number}> = {id = 1, name = "Iron Sword", data = {damage = 25}}
local potion: Item<{heal: number}> = {id = 2, name = "Health Potion", data = {heal = 40}}
-- 用下一个可用的 id 创建物品,保存并返回它
local function addItem<T>(inventory: {Item<T>}, name: string, data: T): Item<T>
local item: Item<T> = {id = #inventory + 1, name = name, data = data}
table.insert(inventory, item)
return item
end
type Weapon = Item<{damage: number}>
type Potion = Item<{heal: number}>
local weapons: {Weapon} = {}
addItem(weapons, "Iron Sword", {damage = 25})
addItem(weapons, "Fire Axe", {damage = 40})
-- 具有此 id 的物品,如果没有则返回 nil
local function findItem<T>(inventory: {Item<T>}, id: number): Item<T>?
for _, item in ipairs(inventory) do
if item.id == id then
return item
end
end
return nil
end
local potions: {Potion} = {}
addItem(potions, "Health Potion", {heal = 40})
-- 每种物品对应一种描述
local function describeWeapon(item: Weapon): string
return `Weapon: {item.name} (damage {item.data.damage})`
end
local function describePotion(item: Potion): string
return `Potion: {item.name} (heals {item.data.heal})`
end
-- 试试看
print(describeWeapon(weapons[2]))
print(describePotion(potions[1]))
Luau 入门中的所有课
自己练习: Luau 在线编译器