Значения разных типов

Поток управления / Условные операторы / Операторы switch/case

local Tiger = {}
Tiger.__index = Tiger

-- Exact values are checked first
local exact = {[2] = "two",
               Error = "Error string"}

-- The keys are the names that type() returns
local by_type = {
  ["nil"] = function() return "Empty value" end,
  number = function() return "Number type" end,
  string = function(text)
    return "string value '" .. text .. "'"
  end,
}

local function describe(value)
  local known = exact[value]
  if known then
    return known
  end
  -- For type() an object is just a table
  if getmetatable(value) == Tiger then
    return "Tiger!!!"
  end
  local handler = by_type[type(value)]
  if handler == nil then
    return "Unknown type"
  end
  return handler(value)
end

local tiger = describe(setmetatable({}, Tiger))
-- tiger = Tiger!!!
local two = describe(2)
-- two = two
local text = describe("test")
-- text = string value 'test'
local whole = describe(5)
-- whole = Number type
local fraction = describe(3.14)
-- fraction = Number type
local empty = describe(nil)
-- empty = Empty value
local flag = describe(true)
-- flag = Unknown type

print("tiger = " .. tiger)
print("two = " .. two)
print("text = " .. text)
print("whole = " .. whole)
print("fraction = " .. fraction)
print("empty = " .. empty)
print("flag = " .. flag)