lua-users home
lua-l archive

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


Hi,

I do use it from time to time if there is either only one function in the module, or there is one function that is that more important than the others that it is worth to emphasize it this way. That may be particularly nice if you use the module as OO classes, and calling them creates a new object.

local circle = require"circle"( x,y, 100 )

(and if you put a copy of require named "new" into the globals, things start to look familiar:)

local rectangle = new "rectangle"( 10,20,80,60 )


I have used calling a module as such in my md5 library whose main function is to compute - what else - a MD5 hash.
That can be written in a single command: MD5 = require"md5"( message )

--
Oliver


Am 22.07.2016 um 15:40 schrieb Peter Aronoff:
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