lua-users home
lua-l archive

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


* Matthew Wild:

> See when I last brought this issue up:
> http://lua-users.org/lists/lua-l/2010-01/msg00411.html (the thread is
> an interesting read, even though it doesn't present an effective
> solution).

I think you might be approaching this from the wrong end.

The code below dumps Lua source code for a module which contains a
single function, run(), which you can use to invoke the main program.
It effectively isolates the main program from unwanted global table
manipulation.  You might want to override "require" in some way
because as it stands, you must use the returned value.

This kludge is still not compatible with lexical environments, but I
guess it is conceptually simpler and achieves much the same effect
because it doesn't need mucking with metatables.

But I think it's still worth fixing the defaults provided by Lua.

print([[
local _G = _G
module(...)

local prototype = {]])
for k, _ in pairs(_G) do
   if k ~= "_G" then
      print(string.format("  [%q] = _G[%q],", k, k))
   end
end
print([[
}

function run(main, ...)
   local g = {}
   for k, v in _G["pairs"](prototype) do
      g[k] = v
   end
   g["_G"] = g
   _G["setfenv"](main, g)
   return main(...)
end
]])