Custom metafields: a simple underexercised solution to the Lua library interoperability problem

by Taylor Richberger

The Problem

Lua is a very simple language. It provides and prescribes very little, allowing the programmer plenty of creativity to solve any problem. It's not long, however, before you need to use third-party library code, though, or to write more comprehensive functionality yourself for reuse. Lua does not even give you a memory buffer type, which you'd need for working with native functions. This means that every library that needs a mutable native memory buffer ends up with one of the following solutions:

  • Inventing their own:
    • Lots of reinventing the wheel, complete with all the bugs and avoidable issues that implies.
    • No interoperability at all. If you want to fill a buffer in one library and then use it in another, you're S.O.L.
  • Reaching for a de-facto standard one, like lua-memory, making everybody dependent on the same thing.
    • Fixes the interoperability issue, but only for libraries that have gotten the memo.
    • API changes cause brittleness. Unless the shared module is extremely simple and small, it will almost always change to some degree at some point. Two libraries trying to use different API versions of the same library breaks everything.
    • If the shared library becomes unmaintained, the whole ecosystem has to either hotpatch it out or migrate off of it.
    • If the shared library has or develops misfeatures along the way, you have to warn people to not use those features (e.g. "This library holds onto pointers from the memory buffer. Do not resize the buffer that you construct our types with, or you will leave us with dangling pointers!").
  • Hacking around it by leaning heavier on standard types, like sequence tables of byte integers, or strings that you copy to internal buffers for the call and then to a fresh string afterward.
    • Performance typically gets terrible, you run a higher risk of accidentally mutating immutable memory in an actual Lua string.

The problem stems from the basics of interoperability. If you get an object that you expect to act like a buffer, how do you treat it like a buffer without inspecting it with something like luaL_checkudata and messing with its internals?

Solutions

The better solution would be to allow an ecosystem of buffer types, any of which can be used with any library that needs buffer types. This means that you couldn't check the userdata type (or ideally even bother with it being a userdata type at all). Instead, you have to operate on the shape and behavior of the data. I can see two obvious approaches to this.

Duck typing

The first and most obvious approach is duck typing. You take a buffer object and expect it to expose the given methods, and call them to do the operations you expect. You still have to agree on the interface (in this case, things like :size() returning an integer and :pointer() returning a light userdata). This is easy enough, and plenty of programming languages use this to a large degree; the way Python and most duck-typed languages interact with the write() method is the clearest example. The downside is API collision. write() can mean vastly different things for different types, and this makes it harder for a single object to adhere to multiple different protocols, and easier for an object to accidentally implement an existing protocol in an incompatible way.

The ideal is that an object that wants to implement a protocol always implements it right, and an object that doesn't intend to implement a protocol implements none of it by mistake.

But on the subject of Python, it already many most of these protocols via dunder-methods (or really dunder-fields, given things like __slots__). Lua doesn't often do that, but rather defers to the metatable for things like this. This is the solution that I think is the most flexible and robust.

Metafield protocols

Lua already expects you to use the metatable to declare things about an object's behavior. You can override operators with __add and friends, customize finalization with __gc, and many other things with the core language. This might seem like it's reserved to the core language functionality, but plenty of the standard library uses things like this too, with __pairs allowing you to specify custom iteration for pairs() and __tostring and __name allowing you to customize how things are printed via tostring.

I believe that this is the way that library code should act as well. Define a protocol that lives in the metatable with a simple, strict interface, and act upon the metafields.

Some third-party libraries already use this pattern. dkjson uses __tojson and a handful of other metafields. serpent uses __serialize to enable you to customize serialization. This is great, but in my mind, there are still quite a few issues:

  • This is very much not a widely used pattern. A few libraries use it, but the ecosystem as a whole doesn't respect this much at all.
  • These names still use the double-underscore prefix. The standard library only uses double-underscores for their metafields, and defines nothing else that should or shouldn't be in the metatables. It is not explicitly stated, but the pattern is clearly that all standard lua metafields will be double-underscore prefixed. This means that library code should all use names that don't have this prefix.
  • These metafields use simple, easily-collidable names. It's incredibly feasible that two unrelated libraries will each define a serialize metamethod with different shapes, causing confusion.

I propose that libraries follow these rules for interoperability:

  • When you want to interact with a type of object that is not best solved by a specific type in the standard library and would benefit from interoperability (i.e. it's not a type that only makes sense in the library itself), use a metafield protocol for it.
  • The metafield names should not be valid Lua identifiers (to accommodate for libraries that follow the poor practice of metatable.__index = metatable).
  • The metafield names should be namespaced in a way that prevents collision. Any approach works, but the following are the most obvious:
    • An owned URI (e.g. {['https://forge.axfive.net/Taylor/bytesview#mutable'] = function(...) ... end})
      • This gives a programmer or user an easy way to find the documentation for the protocol.
      • Sub-protocols are a little bit more awkward, if you can't just arbitrarily add path segments. Fragments can work alright.
    • A reverse-DNS notation name (e.g. {['net.axfive.bytesview.mutable'] = function(...) ... end})
    • An owned luarocks name prefix (e.g. {['bytesview:mutable'] = function(...) ... end})
      • This is shorter and easier to write, and if people get used to it, allows finding the documentation for the protocol easily enough as well. The rock can provide convenience functions to make working with the protocol easier (but this rock should in no way be mandatory for using the protocol).

So why use metafield protocols over duck typing? To be honset, it depends on the protocol in question. Something like I/O would probably do better with duck typing, the way Python does it, but often you want some functionality present for interoperability that don't really make sense to invoke directly from user code. When they are solely adding functionality when used in other libraries, they should probably go in the metatable. This is why Python uses dunder fields, and JavaScript uses well-known Symbols.

Worked solution: bytesview

I have worked on a protocol and utility library for the exact case of buffers: bytesview. That repository covers the use of it well enough, but the long and short of it is something like:

  • bytesview:mutable may be implemented to communicate that the object acts as a mutable memory buffer. You implement it by creating it as a function in the metatable, which returns either a light userdata or another bytesview:mutable, an optional offset, and an optional size. This makes it easy to wrap and/or constrain bytesview objects.
  • bytesview:readonly may be implemented to communicate that the object can act as a readable memory buffer (additionally, strings and bytesview:mutable automatically are considered bytesview:readonly as well, as they can be used in a readonly context).

Conclusion

I don't have any expectation that people will actually start using this. Interoperability in Lua seems to be largely an unsolved problem because nobody cares to work on it. The Lua ecosystem is a couple large dependencies like dkjson and lpeg, but everybody else largely reinvents the same wheels aside from those. The ecosystem is legitimately very small for such a widely-used and well-known language. LuaRocks gets an average of about 2 package uploads every hour.

Still, it would be nice to have more pluggability in a language like Lua, which is built on a philosophy of simple extensibility in the first place. I hope that more libraries that do things like serialization design protocols like this with the expectation that they will be implemented and used completely apart from the library. Something like Rust's Serde built using serde:serialize and serde:deserialize metamethods in Lua would be an obvious use: a serialization and deserialization protocol, leaning on a shared data model, using a different library for each format.

Lua is just such a cool language (with some warts; I won't bring up 1-indexing because it's a boring and overdone discussion, but iterators are seriously weak in Lua), and it's a bit sad to dig around in the ecosystem and see a ton of tiny little fiefdoms instead of robust libraries that can work with one-another.