it's a bug or feature? Lua@OpenComputers@minecraft

237 views Asked by At
local e={print=print, load=load, a='2'}
e._G=e
load(
[[
  print(a) 
  load("print(a)")()
]]
, '', '', e)() 

--expected result

2
2

--but in reality

2
1

Why does "load" not get the environment for the compiled chunk from the environment?

1

There are 1 answers

11
user3125367 On BEST ANSWER

http://www.lua.org/manual/5.2/manual.html#pdf-load

If the resulting function has upvalues, the first upvalue is set to the value of env, if that parameter is given, or to the value of the global environment.

I.e. no matter where you are now in terms of _ENV, missing env argument to load will connect loaded chunk to very global environment.

If you want the loaded source in 5.2 to inherit new environment by default, substitute load / loadfile functions:

e.load = function (ld, src, mode, env)
    return load(ld, src, mode, env or e)
end