布尔参数的默认值
本课属于 Coddy Lua 学习旅程的“Luau 入门”单元。第 28 课,共 80 课。
你从 Lua 中已经知道一个注意点:or 也会替换 false。对于默认值应为 true 的 boolean? 参数,flag = flag or true 会把显式传入的 false 变成 true,因为 false or true 的结果是 true:
local function sendAlert(message: string, loud: boolean?)
loud = loud or true -- 调用 sendAlert("Hi", false) 时,loud 最终仍是 true
print(message, loud)
end请改用显式的 nil 检查。只有省略参数时,它才会填入默认值:
local function sendAlert(message: string, loud: boolean?)
if loud == nil then
loud = true
end
print(message, loud)
end
sendAlert("Hi") -- Hi true
sendAlert("Hi", false) -- Hi false对于字符串和数字,使用 or 是安全的,因为只有 nil 和 false 会被视为假值。
挑战
简单为布尔参数设置默认值 true,且不能用 false 覆盖它。
- 编写
local function shippingCost(weight: number, insured: boolean?): number。 - 在函数开头写上
if insured == nil then insured = true end。 - 当
insured为 true 时返回weight * 0.5 + 2,否则返回weight * 0.5。 - 打印
shippingCost(4)和shippingCost(4, false)。
按“运行代码”:输出以 4 和 2 结尾。
亲手试试
-- 用 `or` 的常见写法设置默认值
local function calculateTax(price: number, rate: number?): number
rate = rate or 0.05
return price * rate
end
print(calculateTax(100))
print(calculateTax(200, 0.08))
Luau 入门中的所有课
自己练习: Luau 在线编译器