项目:库存物品
本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 67 课,共 80 课。
挑战
简单先用一种通用物品类型初始化背包。
- 在物品上方,写入
type Item<T> = {id: number, name: string, data: T}。 - 为它们添加类型注释:
local sword: Item<{damage: number}>和local potion: Item<{heal: number}>。 - 在
-- Try it下方,添加print(potion.data.heal)。
按下运行代码:输出会显示 Iron Sword 和 40。
亲手试试
-- 在这里添加 Item<T> 类型
local sword = {id = 1, name = "Iron Sword", data = {damage = 25}}
local potion = {id = 2, name = "Health Potion", data = {heal = 40}}
-- 试试看
print(sword.name)
Luau 入门中的所有课
自己练习: Luau 在线编译器