Learn Lua · Errors and nil · Lesson 1 of 4

Stopping with an error

When a script can't do its job, it should stop and say why. error("message") stops the script with that message, and assert(condition, "message") stops it when the condition is false:

LUA
local ok, message = pcall(function() error("No quantity given", 0) end)
message  --> "No quantity given"

(pcall, which catches the error here so you can see it, has a lesson of its own later in this unit.) The 0 after the message leaves out the line number that Lua would otherwise put in front of it. A clear message saves whoever reads the run's error from guessing what went wrong.

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 = { quantity = 3 }

Steps

  1. Stop with an error that mentions quantity when input.quantity is missing.
  2. Stop with an error that mentions at least 1 when the quantity is less than 1.
  3. Otherwise return { quantity = input.quantity }.
Show a hint

Check for a missing quantity before you compare it with 1: comparing nil with a number is itself an error.