local inch_size = 15
-- 没有 switch:用 elseif 链,
-- 每组值一个分支,else 作为默认分支
local verdict
if inch_size == 14 or inch_size == 15 then
verdict = "too small"
elseif inch_size == 16 or inch_size == 17 then
verdict = "good for the past decade"
elseif inch_size == 24 or inch_size == 27 then
verdict = "great choice"
else
verdict = "unknown size"
end
-- verdict = too small
-- 或者用函数表:键就是 case
local function too_small()
return "too small"
end
local function good()
return "good for the past decade"
end
local function great()
return "great choice"
end
local function unknown()
return "unknown size"
end
local handlers = {
[14] = too_small, [15] = too_small,
[16] = good, [17] = good,
[24] = great, [27] = great,
}
local function describe(size)
-- 没有匹配时得到 nil:由 or 选择默认值
local handler = handlers[size] or unknown
return handler()
end
local by_table = describe(inch_size)
-- by_table = too small
local missing = describe(32)
-- missing = unknown size
print("verdict = " .. verdict)
print("by_table = " .. by_table)
print("missing = " .. missing)