lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 22 Jul 2016 06:40, "Peter Aronoff" <telemachus@arpinum.org> wrote:
Patrick Donnelly <batrick@batbytes.com> wrote:
> For some slightly early "It's Friday" discussion, what do you use the
> __call metamethod for? Discuss your favorite hacks, strange problems
> solved, code golf hole-in-ones, etc.

Here’s one that somebody suggestsed for a module of mine. The module is
named split, and the primary method is also split. So if you require it in
a conventional way, you get this:

        local split = require "split"
        local record = "foo,bar,bizz,buzz"
        local fields = split.split(record)

To avoid the redundancy, he suggested packaging the module this way:

        return setmetatable({
          split      = split;
          -- various other methods
        },{
          __call = function(_, ...)
          return split(...)
        end
        })

So now a user can require the module as normal, but call split using the
module alone. I didn’t do it at the time—I thought that it was too magic
and unnecessary since it’s easy for a user to assign the method to whatever
short name they like when they require the module.

But now I’m curious: is this pattern common in other Lua modules? I don’t
think I’ve seen it, but perhaps I haven’t seen enough.

Best, P
--
We have not been faced with the need to satisfy someone else's
requirements, and for this freedom we are grateful.
    Dennis Ritchie and Ken Thompson, The UNIX Time-Sharing System

I used to often return functions from modules.
I now return tables, but to keep compatibility I give them a __call metamethod.