默认值

数组和集合 / 字典

local dic = {one = "A", two = "B"}

-- nil 表示键不存在:or 给出默认值
local value = dic.three or "-"
-- value = -

-- 默认值也一并存入
dic.three = dic.three or "-"
-- dic.three = -

-- 计数:不存在的键从 0 开始
local scores = {}
scores.ann = (scores.ann or 0) + 1
-- scores.ann = 1

-- 陷阱:or 也会替换已存储的 false
local flags = {sound = false}
local sound1 = flags.sound or true
-- sound1 = true

-- 检查是否为 nil,以保留 false
local sound2 = flags.sound
if sound2 == nil then
  sound2 = true
end
-- sound2 = false

-- 一次为所有缺失的键设置默认值
local counters = setmetatable({}, {
  __index = function()
    return 0
  end,
})
counters.ann = counters.ann + 1
-- counters.ann = 1
local bob = counters.bob
-- bob = 0

print("value = " .. value)
print("dic.three = " .. dic.three)
print("scores.ann = " .. scores.ann)
print("sound1 = " .. tostring(sound1))
print("sound2 = " .. tostring(sound2))
print("counters.ann = " .. counters.ann)
print("bob = " .. bob)