Lua Fundamentals

Lesson 5 of 6

Metatables and Modules

Metatables: customizing table behavior

A metatable is a table attached to another table that defines how it behaves for operations it doesn't natively support, like addition, or missing-key lookups. This is how Lua achieves "object-oriented programming" without a built-in class keyword.

Lua
  • setmetatable(t, mt) attaches metatable mt to table t.
  • __index is a special metamethod: when you look up a key that v doesn't have directly (like length), Lua checks __index next, this is how "instances" share methods defined on a common table.
  • function Vector:length() is sugar for function Vector.length(self), the colon automatically adds a hidden self first parameter, and v:length() automatically passes v as that self.

Modules

Lua organizes reusable code into modules: files that return a table of functions. In a real project this would be two separate files:

-- mathutils.lua
local M = {}

function M.double(n)
  return n * 2
end

return M
-- main.lua
local mathutils = require("mathutils")
print(mathutils.double(21)) -- 42

require loads a module by name, runs it once, and caches its returned value, calling require again for the same module returns the cached table instead of re-running the file. This course's sandbox only runs one file at a time, so here's the same idea inlined into a single runnable script:

Lua

TIP

If you've used JavaScript's ES modules or Python's imports, require will feel familiar, the key difference is that a Lua module file explicitly returns the table of things it wants to expose, instead of using an export keyword.

📝 Metatables & Modules Quiz

Passing score: 70%
  1. 1.Which metamethod lets a table fall back to another table when a key is missing?

  2. 2.Calling require("mathutils") twice runs the mathutils.lua file twice.

  3. 3.The function used to attach a metatable to a table is ____(t, mt).