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.
setmetatable(t, mt)attaches metatablemtto tablet.__indexis a special metamethod: when you look up a key thatvdoesn't have directly (likelength), Lua checks__indexnext, this is how "instances" share methods defined on a common table.function Vector:length()is sugar forfunction Vector.length(self), the colon automatically adds a hiddenselffirst parameter, andv:length()automatically passesvas thatself.
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:
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.