lua-users home
lua-l archive

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


On Tue, Jul 21, 2009 at 10:05 AM, startx<startx@plentyfact.org> wrote:
> dofile 'mylib.lua'
>
> or if i should use the pure lua module format and load make it avalable
> with
>
> require 'mylib'

Ultimately, there isn't much difference;  creating modules is a useful
way to load code from a set of standard locations, and require() will
not load code _twice_ since the loader keeps track of loaded modules.
You do not have to use module() to make something available using
require(), as long as the file is on LUA_PATH.  In that case you do
have to explicitly say 'function myproject.fun() ' etc and actually
create the table myproject explicitly.

The downside of require() is that it works from LUA_PATH.  Python has
a cute feature that 'import' will automatically pick up a module in
the same directory as the importing file; Lua doesn't do that.  It's a
question of where you want to put files. If it is an application then
using dofile() to stitch things together is not a bad idea (although
watch out for including things repeatedly!).  If these libraries are
meant to be used in other Lua programs then require() makes sense and
they should sit somewhere on LUA_PATH (which can be modified if
necessary)

You can modify the value of package.path before you call require(),
which gives another deployment option.

> 2) my second question is about the use of namespaces: as i have quite
> a lot of functions, i would like to use a "subnamespace" to group the
> functions to something like:
>
> myproject.core.do_something()

It's actually a common pattern, e.g. look at LuaSocket.   If on the
LUA_PATH there is a directory myproject, which contains core.lua, then
require 'myproject.core' will pull it in. If you use module() then the
'namespaces' are automatically created for you.

steve d.