Logo with title ".Blog"

Metatables suck

Published on

In response to Metatables suck.

Metatables: I use metatables to signal the separation of data and behavior. Data goes in the table, behavior goes in the metatable. Great for debugging; the debugger isn’t cluttered with a bunch of methods.

Encapsulation: I don’t actually want true encapsulation, because it’s harder to debug. Unlike local variables, private fields can be tapped into, and I don’t have to hunt them down in the debugger. Also makes writing tests easier.

Overloading: I agree in principal, but in practice, sometimes the convenience is too much to pass up. To reconcile this, I always accompany a non-obvious metamethod behavior with an equivalent method.

But it’s worth noting that metamethods are harder to debug, because they don’t allow yielding, so you can’t set breakpoints in them. That’s why it’s good to have a regular method-based equivalent.