lua-users home
lua-l archive

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


On Dec 6, 2011, at 8:48 PM, Ezequiel García wrote:

> 1. I must create a table.
> 2. Assign it a metatable with the __call metamethod.
> 3. This __call method will perform the module init.

Yes.

> But, what if I don't pass any parameter to require? 
> Will it call metamethod __call ?

No. You need to invoke it explicitly in that case.

local Foo = require( 'Foo' )
local aFoo = Foo()

FWIW, I use the above idiom quite extensively in various Lua projects.

Pedestrian example:

local DB = require( 'DB' )
local aDB = DB( 'sqlite3://localhost/test.db' )

for aContact in aDB( 'select * from contact' ) do
    print( aContact.name, aContact.email )
end

Gory implementation details:

http://dev.alt.textdrive.com/browser/HTTP/DB.lua#L65

I personally tend to expose my modules functionalities exclusively through metamethods (__call, __index, __newindex mostly). While this might sounds limiting at first, it turns out to work rather well in practice. But, as always, YMMV.