lua-users home
lua-l archive

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


2009/7/21 Sam Roberts <vieuxtech@gmail.com>:
> On Tue, Jul 21, 2009 at 1:21 AM, steve donovan<steve.j.donovan@gmail.com> wrote:
>> On Tue, Jul 21, 2009 at 10:05 AM, startx<startx@plentyfact.org> 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:
>>>
>>> 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.
>
> 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
> tell.
>
>
>
> ~/w/wt/achilles-engine % lua
> Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
>> require"hi.bye"
>> = hi
> nil
>> 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
> module("bye")
>
> 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
be:

% cat hi/bye.lua
module(...)
name = "I am bye"

Also the module function defines some useful variables, which can be
used to look for relative modules:

% cat hi.lua
module(..., package.seeall)
local bye = require(_NAME..".bye")
print(bye.name)

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.