Metatables are Lua's secret weapon. In this episode we learn how to attach custom behavior to tables: setmetatable to assign a
metatable, __tostring for print output, __add and __eq for operator overloading, and __index for fallback lookups — the
foundation for OOP in Lua.
Every keystroke is shown on screen with 3-second pauses so you can follow along at your own pace.
What You'll Learn:
setmetatable(t, mt) — attaching a metatable to a table
__tostring — custom string representation for print
__add — overloading the + operator for tables
__eq — custom equality comparison
__index — fallback lookup when a key is missing
How Lua checks the metatable on every operation
Student Code: https://github.com/GoCelesteAI/learn-...
Timestamps:
0:00 Intro
0:12 Preview
0:44 __tostring — Custom Print Output
2:53 Run __tostring
3:04 Vector Class with __add
6:21 Vector Run — Addition & Equality
9:07 __index as Fallback
12:27 Final Run
12:47 Recap
13:19 Endscreen
Key Takeaways:
1. setmetatable attaches a metatable that controls table behavior
2. __tostring defines how a table prints as a string
3. __add and __eq let you overload operators for tables
4. __index provides a fallback when a key isn't found
5. Metatables are the foundation for OOP and inheritance in Lua
This is Episode 29 of the Learn Lua in Neovim series. New episodes cover OOP with metatables, the Neovim Lua API, and writing
your first Neovim plugin — all coded inside Neovim.
Taught by CelesteAI. Like & subscribe for more tutorials!
#lua #neovim #programming #tutorial #beginners #learnlua #luaprogramming #neovimtutorial #luametatables #luametamethods #coding
Tags
lua, lua tutorial, learn lua, lua metatables, lua metamethods, lua setmetatable, lua __tostring, lua __add, lua __eq, lua
__index, lua operator overloading, lua fallback lookup, lua custom behavior, lua for beginners, neovim lua, neovim tutorial,
learn lua in neovim, lua episode 29, programming tutorial, coding tutorial, intermediate programming, lua 2026, neovim 2026,
screenkey, code along, lua advanced, lua table behavior