lua-users home
lua-l archive

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


You can keep the original 'arg' using a setfenv trick in Lua 5.1:

function dofile(filename, ...)
   local env = setmetatable({ arg = {[0] = filename, ...} },
                            { __index = _G, __newindex = _G })
   return setfenv(assert(loadfile(filename)), env)(...)
end

This will look up 'arg' in the 'env' table, and everything else
(including writes) will be done in '_G'.

I find arg[-1] (the name of the Lua executable) to be very useful, here's a version that preserves that value in the arg table:

function dofile(filename, ...)
   local env = setmetatable({ arg = {
         [-1] = arg and arg[-1], -- Lua executable
         [0] = filename, -- Lua script
         ... -- Script arguments
      }},
      { __index = _G, __newindex = _G })
   return setfenv(assert(loadfile(filename)), env)(...)
end

 - Peter Odding