lua-users home
lua-l archive

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


Hi,

I think we should stimulate users to use the

    local lib = require"lib"

idiom. It is not too much work and it does bring a nice and clean
independence.  Jamie Webb has a point and perhaps there shouldn't
even *be* an "import" function.

I really like Roberto's idea of libraries setting globals for stuff they
want to export, and keeping local what they want to hide. I have been using
something similar to this and I think it's the most natural solution of all
so far.

I would like the library conventions to be the simplest possible.  That way,
implementors are more likely do use it even for small projects.  What if
the "require" and "requirelib" functions did the nasty part? They could even
accept the optional table from the user, so that different libraries can
share the same environment:

    -- pseudo-code ahead
    function require(libname, namespace)
        -- if it's already there, just return it
        if _LOADED[libname] then return _LOADED[libname] end
        -- if no namespace was provided, create a new one
        namespace = namespace or {}
        -- move basic stuff to the namespace, probably by __index trick
        clone(_G, namespace)
        namespace._REQUIREDNAME = libname
        -- find the library using path search, perhaps
        local init = loadfile(find(libname))
        -- make sure library globals go to the namespace
        setfenv(init, namespace)
        -- store namespace in _LOADED to prevent recursive problems
        _LOADED[libname]  = namespace
        -- run the loader and return the namespace to the user
        init()
        namespace._REQUIREDNAME = nil
        return namespace
    end

I think the cloning should be done via the __index metamethod to the
namespace table, to avoid copying and prevent garbage from showing up when
you iterate the namespace for its contents.  Even if we were to copy base
lib into the namespace, there are only 32 symbols for the current Lua
version.

I think that string, io, table, math etc should *not* be special
in any sense and should adopt the same idea.

Would everyone be happy?

[]s,
Diego.