lua-users home
lua-l archive

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


Roberto wrote:
Namespaces is only one of the uses of the global declaration. But remember
that, in Lua, almost every function is global (print, write, etc.), so
a simple "namespace T" would not be very helpful. Moreover, a simple
"namespace T" helps to define modules, but not to use them.

OK I think I've got it, thanks for your reply. I was trying to fit the square peg in the round hole.

The semantics is: "global (exp) name-list" translates to

  _temp = exp

after that, any use of a name in name-list is read as "_temp.name",
subjected to the usual visibility rules for variable declarations.
If name-list is '*', then the rule applies to any name not declared
in another local/global declaration.

So stated another way, this is a mapping from bare names in the current scope to tables.

Usually some mapping that doesn't use the native tables is cause for attention, but I understand in this case you want it to be efficient and avoid the runtime lookup. This means that the name-list must consist of literals. However dynamic routing is still possible, by mapping * to T and then doing tricks with T's metatable.

Going back to your original post:

In my understanding, we all agreed that most parts of a good module
system can be done in Lua itself. But such system can become quite
complex and even may use non-standard facilities (e.g. use of timestamps
to re-load modules that have been modified since they were loaded;
or hierarchical namespaces mapped to directories hierarchies, as in
Python). Therefore, it would be a good idea to provide it outside the
main distribution, through libraries and conventions.

If I'm correct that the global statement only applies within the current scope, then the functionality can't be wrapped by some higher level system. So it wouldn't be possible to do:

    FancyImport('foolib', {'a', 'b', 'c'}) -- use a, b, c from foolib

A little more complex example is

  global (metatable({}, {index=globals()})) *

That puts all new names in a private table, but inherits all global names.

One subtle problem with this technique, assuming it was used at chunk scope, is that someone may later switch the global table (say by copying the current global table and adding a few items). Then this chunk would be left accessing some table that is not the global table. If modules start doing this there may need to be a policy in place about the global table.


-John


--
OpenPGP encrypted mail welcome.