可选参数
本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 26 课,共 80 课。
在原生 Lua 中,你可以一直省略参数:缺少的参数会静默地变成 nil,而忘记处理这种情况是 bug 的常见来源。Luau 会明确标记这种可能性:在参数的类型后添加 ?,将其标记为可选。
function greet(name: string, title: string?): string
if title then
return `{title} {name}`
end
return `Hello, {name}`
end
print(greet("Ada")) -- Hello, Ada
print(greet("Ada", "Dr.")) -- Dr. Adastring? 表示“string 或 nil”。调用者可以传入字符串,也可以完全跳过这个参数;没有 ? 的参数是必需的,检查器会标记省略这些参数的调用。
在函数内部,可选参数可能是 nil,所以使用前要先检查:if title then ... end 是标准写法。如果跳过检查并将 nil 拼接到字符串中,就会得到 Lua 一直以来都会报的同一种运行时错误;类型检查器会提前警告你。
挑战
简单编写一个显示名称可选的个人资料函数。
- 编写
local function createUserProfile(username: string, displayName: string?): string。 - 如果提供了
displayName,则返回`Profile: {displayName} (@{username})`,否则返回`Profile: @{username}`。 - 打印
createUserProfile("john_doe", "John Doe")和createUserProfile("jane_smith")。
点击运行代码:输出会显示 Profile: John Doe (@john_doe) 和 Profile: @jane_smith。
亲手试试
-- 1)createUserProfile(username: string, displayName: string?): string
-- 2)分别在有显示名称和没有显示名称时打印结果
Luau 入门中的所有课
自己练习: Luau 在线编译器