LUA / CHAPTER 11

Metatables and protected calls

Advanced

Add object-like behavior and handle expected failures deliberately.

By the end of this chapter

  • Use __index for method lookup
  • Trace colon calls and self
  • Inspect pcall success and failure results

The idea

A table can have a metatable that defines behavior for selected operations. Setting __index to a method table lets missing fields be looked up there, which supports a simple object-like pattern. The colon call object:method(value) passes object as the first argument, matching a method whose first parameter is self. Keep per-instance data on each instance rather than placing shared mutable state accidentally in the method table.

error raises a failure, and pcall invokes a function in protected mode. Its first result reports whether the call succeeded; following results contain either the function’s return values or the error object. Check that status before treating the second result as ordinary data. Handle a failure at a boundary that can make a useful decision instead of silently converting every programming mistake into success.

Lua example
local Counter = {}
Counter.__index = Counter
function Counter:add(amount) self.value = self.value + amount end
local item = setmetatable({value = 2}, Counter)
item:add(3)
local ok, result = pcall(function() return item.value end)
print(ok)
print(result)
Result
true
5

The method is found through __index, and the colon supplies item as self. The protected function succeeds and returns the updated value after the status boolean.

Try it yourself

Write a checked parser that raises an error for a nonnumeric string, then display a useful result from pcall.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which call is equivalent to item:add(4)?