Learn Lua · Errors and nil · Lesson 4 of 4

Catching errors

pcall runs a function and catches any error it raises. It returns true and the function's results, or false and the error message:

LUA
local function parse(text)
  local n = tonumber(text)
  if n == nil then error("not a number: " .. text, 0) end
  return n
end

local ok, value = pcall(parse, "42")
ok     --> true
value  --> 42
local failed, why = pcall(parse, "lots")
failed  --> false
why     --> "not a number: lots"

Catch errors when you can carry on without the failed part, and let them stop the script when you can't.

What your code receives

Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.

LUA
input = { values = { "3", "lots", "4.5" } }

Steps

  1. Return numbers: every value in input.values that parse accepts, as numbers, in order.
  2. Add problems: how many values parse refused.
  3. Add firstProblem: the first refusal's message, or nil when there were none.
Show a hint

Loop over input.values, call pcall(parse, text) for each, and keep the value or count the problem.