[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: How to properly initialize a module?
- From: Petite Abeille <petite.abeille@...>
- Date: Tue, 6 Dec 2011 21:56:33 +0100
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.
> 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.
local DB = require( 'DB' )
local aDB = DB( 'sqlite3://localhost/test.db' )
for aContact in aDB( 'select * from contact' ) do
print( aContact.name, aContact.email )
Gory implementation details:
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.