lua-users home
lua-l archive

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


On Sun, 2011-01-02 at 17:11 +0100, Patrick Rapin wrote:
> function dofile(filename, ...)
>         arg = {[0] = filename, ...}
>         return assert(loadfile(filename))(...)
> end
> 
> I know this is not 100% correct, since the global 'arg' variable is
> not restored after the call. 

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'.