Since 'w' never appears outside 'loadstring', the local 'w' is irrelevant, and you can get rid of the '_ENV'. (Once you do that, Lua 5.1 also runs the snippet.)
I get it now; _ENV basically acts like the _G table. (but does something else as well).
I was looking for a way to use _ENV to do the same setfenv functionality from lua 5.1, and did it wrong.
I searched for it on the 'net, found this "loadin" function, but its not in my lua 5.2 beta!
Lua 5.2.0 (beta) Copyright (C) 1994-2011 Lua.org, PUC-Rio > print(loadin) nil
If there's no such function I'd have to do something like:
local pairs = pairs local function copy(from, to) for k, v in pairs(from) do to[k] = v end end local function clear(t) for k, v in pairs(t) do t[k] = nil end end
local function use(env, fun) local _env = {} copy(_ENV, _env) clear(_ENV) copy(env, _ENV) local result = {fun()} copy(_ENV, env) clear(_ENV) copy(_env, _ENV) return table.unpack(result) end
On Thu, Sep 15, 2011 at 08:36:09AM +0200, Eric Man wrote:
If you run the code snippet, it'll print "= a<a<". I'd have thought it would be "= a<<.>a<<.>>".
If you toggle line 4 off, though, it will print "= a<<.>a<<.>>" as expected.
... local function test(bool)
local w, t
if bool
--or true --- toggle this line
then
t = "a"
w = function (s) t = t .. tostring(s) end
_ENV.w = w
else
t = "."
end
Since 'w' never appears outside 'loadstring', the local 'w' is irrelevant, and you can get rid of the '_ENV'. (Once you do that, Lua 5.1 also runs the snippet.) The above code simplifies to local function test (bool) local t if bool then t = "a" function w(s) t = t .. tostring(s) end else t = "." end Whereas the code below, since the 'or true' means the condition always holds local function test(bool)
local w, t
if bool
or true --- toggle this line
then
t = "a"
w = function (s) t = t .. tostring(s) end
_ENV.w = w
else
t = "."
end
simplifies to local function test (bool) local t = "a" function w(s) t = t .. tostring(s) end Dirk
|