lua-users home
lua-l archive

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


Hi,

in some libraries I am working on I lazily load "sub-modules", i.e.

local mylib = require "mylib"
local z = mylib.xxx.z -- here the sub-module xxx is loaded which contains z

this is easily achieved via the __index metamethod applied to the mylib table. 
In the example above I would have /lua/mylib/xxx.lua required via 'require 
"lib.xxx"'.

Everything is good and simple (I just have to add lua files in the mylib dir), 
but sometimes sub-modules contain too much code for a single lua file (IMHO and 
in my case). At the moment I am solving the issue by having the sub-module (xxx 
above) importing everything (z and much more) from a list of lua files to 
itself:

-- xxx.lua:
local _M = {}
import(_M, require "mylib.xxx_imp.a") -- implementation not shown here.
import(_M, require "mylib.xxx_imp.b") -- I could use dofile as well, xxx_imp not 
"exposed"
...
return _M

This requires me to manually edit the xxx.lua file every time some new 
functionality is added to xxx. It would be nice to be able to have some code 
that allows me to "import" all the lua files in a given directory (xxx_imp 
above) to avoid this manual editing.

I guess this cannot be done via plain lua as it likely requires a library like 
lfs. Moreover I am concerned about how to figure out what directory to look 
into. I always simply used require, but I clearly cannot rely on it here (I 
don't know the lua file-names I would be importing) so I would need to figure 
out a way to discover where to look for "mylib.xxx_imp" as a directory.

Experience has shown to me that it's usually a good idea to keep things simple 
and not over-engineer them, so I am wondering whether there is a much simpler 
solution/approach to the problem I am facing.

Any suggestion is more than welcome :)

Cheers,