Lesson 31 of 55
9 mins readPython Metatables & get/setmetatable
In Plain English
Metatables allow changing the behavior of tables. Using `setmetatable(table, meta)` and `getmetatable(table)`, you can define custom operator handling, fallbacks, and string formatting.
Deep Dive: How It Works
What is a Metatable: A regular table containing special keys called **metamethods** (prefixed with `__`).
setmetatable(t, meta): Sets `meta` as the metatable for table `t` and returns `t`.
getmetatable(t): Returns the metatable associated with `t`, or `nil` if none is set.
Core Rules to Remember

setmetatable(): Attaches a metatable to customize table operations.

Metamethods (__): Special double-underscore keys (e.g., `__add`, `__index`, `__tostring`).
Live Interactive Example
Hit Run Code to see it liveAttaching a Metatable
Python 3.12
1
2
3
4
5
6
7
8
Output Console
Click "Run Code" to view the rendered output.
How it works: setmetatable attached the metadata table to data.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Attach and Read Metatable
Declare `local t = { val = 42 }` and `local mt = { tag = "Secret" }`.
Call `setmetatable(t, mt)`.
Print `"Tag: " .. getmetatable(t).tag`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.