Lua Advanced: Coroutines, Metamethods & Performance

Lesson 2 of 5

Advanced Metatables: Operator Overloading & __call

Fundamentals covered __index for method lookup. Metatables support many more metamethods that let a table respond to operators, comparisons, tostring, and even being called like a function.

Operator overloading

Lua

print(v1 + v2) runs __add to build a new Vector, then print calls tostring on it, which invokes __tostring. Without __tostring, printing a table falls back to Lua's default table: 0x... representation.

__call: making a table callable

Lua

__call is what lets some libraries expose an object that's both a table of methods/config and directly invokable.

__newindex: intercepting new keys

Lua

__newindex only fires when you assign to a key that doesn't already exist in the table, it's the standard trick for building read-only tables, or a proxy that validates/logs writes.

NOTE

There's a matching, easy-to-miss rule: __index (as a function) only fires on a missing-key read, and __newindex only fires on a missing-key write. Once a key genuinely exists on the table itself, both metamethods are bypassed entirely for that key.

📝 Advanced Metatables Quiz

Passing score: 70%
  1. 1.Which metamethod lets a table be invoked like a function, e.g. myTable(10)?

  2. 2.__newindex fires every time you assign to any key on a table, even one that already exists.

  3. 3.Overloading the + operator for a custom table is done by defining the ____ metamethod.