typestar

pcall in Lua

error raises; pcall catches into a status and a message.

-- error raises; pcall catches and turns it into a status return.
local function open_door(name)
  if name == "vault" then
    error("sealed by the old wards")
  end
  return name .. " creaks open"
end

local ok, result = pcall(open_door, "cellar")
print(ok, result)

local ok2, err = pcall(open_door, "vault")
if not ok2 then
  print("Blocked: " .. err)
end

-- assert converts a nil-and-message pair into an error.
local ok3 = pcall(function() assert(nil, "no torch lit") end)
print("Assert survived: " .. tostring(ok3))

How it works

  1. error("...") throws; nothing below it runs.
  2. pcall(f, args) returns ok plus results or the message.
  3. assert(nil, msg) converts a nil into that error.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
510
Tokens
102
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 94 seconds.

Type this snippet

Step 2 of 3 in Patterns & errors, step 21 of 27 in Language basics.

← Previous Next →