简单条件

控制流 / 条件语句 / switch/case 语句

local inch_size = 15

-- No switch: a chain of elseif, one branch
-- per group of values, else is the default
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

-- Or a table of functions: the key is the 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)
  -- No match gives nil: or picks the default
  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)