[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: require vs dofile and how to organise many functions
- From: Jerome Vuarand <jerome.vuarand@...>
- Date: Wed, 22 Jul 2009 14:03:04 +0200
2009/7/21 Sam Roberts <email@example.com>:
> On Tue, Jul 21, 2009 at 1:21 AM, steve donovan<firstname.lastname@example.org> wrote:
>> On Tue, Jul 21, 2009 at 10:05 AM, startx<email@example.com> wrote:
>>> 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:
>> 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.
> Maybe I misunderstand what you mean by "namespaces are automatically
> created for you", because
> it doesn't look like it to me.
> I would expect after require"hi.bye" to be able to access "hi.bye", if
> namespace were created, but that isn't how it works, as far as I can
> ~/w/wt/achilles-engine % lua
> Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio
>> = hi
>> return hi.bye
> stdin:1: attempt to index global 'hi' (a nil value)
> stack traceback:
> stdin:1: in main chunk
> [C]: ?
>> = bye
> table: 0x64bf50
>> return bye.name
> I am bye
> ~/w/wt/achilles-engine % cat hi/bye.lua
> name = "I am bye"
To avoid that problem you can use the parameter passed to modules,
which is the module name. So a better implementation of bye.lua would
% cat hi/bye.lua
name = "I am bye"
Also the module function defines some useful variables, which can be
used to look for relative modules:
% cat hi.lua
local bye = require(_NAME..".bye")
Here require(_NAME..".bye") is used to find a child module. You can
use require(_PACKAGE.."hello") to find a sibling module.
With these constructs you can have your Lua modules really independent
from their path and name, which let you move them between namespaces.