lua-users home
lua-l archive

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


So basically what everyone is saying is that there is no standard for writing modules in Lua 5.2 or 5.1 for that matter? 

On Tue, Oct 5, 2010 at 9:15 AM, steve donovan <steve.j.donovan@gmail.com> wrote:
On Tue, Oct 5, 2010 at 4:05 PM, Mark Hamburg <mark@grubmah.com> wrote:
> Better to not muck with environments at all. The following works just fine
> in Lua 5.1 and 5.2:

In recent code I've gone for this style as well - straightforward, no magic.

> If you insist on mucking with the global environment, you can always add:
> _G[ ... ] = M

That's cute, but it will only work for top-level modules.

Here's something that does work with any dotted namespace, plus an
option to switch it off. It's meant to replace the 'return M' at the
end of a module.

---- split a string into a list of strings separated by a delimiter.
function split(s,re)
   local res = {}
   re = '[^'..re..']+'
   for k in s:gmatch(re) do t_insert(res,k) end
   return res
end

local function export(name,mod)
   local rawget,rawset = _G.rawget,_G.rawset
   if not rawget(_G,'__PRIVATE_REQUIRE') then
       local path = split(name,'%.')
       local T = _G
       for i = 1,#path-1 do
           local p = rawget(T,path[i])
           if not p then
               p = {}
               rawset(T,path[i],p)
           end
           T = p
       end
       rawset(T,path[#path],mod)
   end
   return mod
end

return export(...,M)

Probably evil, but works predictably on both lua 5.1 and 5.2, pleasing
most factions. It is of course something that goes in some utility
library.

steve d.