Menu
CoddyTech

真偽値のデフォルト値

CoddyのLuaジャーニー「Luau入門」セクションの一部。レッスン 28/80。

Luaで知っている注意点が1つあります。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) でも 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

文字列と数値では、偽として扱われるのはnilとfalseだけなので、orを安全に使えます。

challenge icon

チャレンジ

簡単

ブール型のパラメーターに、falseでは上書きできないデフォルト値trueを設定しましょう。

  1. local function shippingCost(weight: number, insured: boolean?): numberと書きます。
  2. if insured == nil then insured = true endで始めます。
  3. insuredがtrueの場合はweight * 0.5 + 2を返し、それ以外の場合はweight * 0.5を返します。
  4. shippingCost(4)とshippingCost(4, false)を出力します。

Run Codeを押します。出力の末尾は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オンラインコンパイラ