Генерация исключения

Обработка исключений

local Seller = {}
Seller.__index = Seller

function Seller.new()
  return setmetatable({cars = {}}, Seller)
end

function Seller:sell()
  if #self.cars == 0 then
    -- Level 0: no position is added to the text
    error("No cars for sale", 0)
  end
end

local seller = Seller.new()
-- pcall(f, a) calls f(a): the method gets self
local _, msg = pcall(seller.sell, seller)
-- msg = No cars for sale

-- Any value can be thrown, for example a table
local _, err = pcall(error, {code = 1})
-- err.code = 1

print("msg = " .. msg)
print("err.code = " .. err.code)