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:
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.
input = { values = { "3", "lots", "4.5" } }Steps
- Return
numbers: every value ininput.valuesthatparseaccepts, as numbers, in order. - Add
problems: how many valuesparserefused. - Add
firstProblem: the first refusal's message, ornilwhen there were none.
Show a hint
Loop over input.values, call pcall(parse, text) for each, and keep the value or count the problem.