[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Arguments of dofile
- From: Michal Kottman <k0mpjut0r@...>
- Date: Sun, 02 Jan 2011 17:28:05 +0100
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'.