lua-users home
lua-l archive

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

> You can get this with load() (and loadfile()) but passing in an empty environment for the chunk.

No, this doesn't cause a syntax error, it causes a runtime error
("attempt to index a nil value" if you set _ENV to nil).  This
requires me to run the user code when they submit it rather than just
compile it (and with enough variations of inputs to try and cover
every branch).

> I'm not sure I understand this.  An example?

A trivial strict environment is just to set _ENV to nil, and then
declare everything as local variables.  This doesn't work exactly the
same way for closures because they can see the locals up the tree
(i.e. upvalues) in addition to their locals.  Most of the examples I
can think of either extend the strict error checking or are hugely
convoluted.  One useful example I can think of is as follows:

local pairs, print = pairs, print
local _ENV = nil

local a = {}
local function b (_ENV) <> -- empty upvalue list
  a, b, c = 10, 20, 30


for k,v in pairs(a) do print(k,v) end

With the `<>` declaring an empty upvalue list the `a,b,c` values are
bound to the `_ENV` parameter.  Without it the compiler prefers to
bind to local variables before _ENV, and so you destroy the table and
function.  If you don't pass in the `_ENV` parameter the code will
actually fail to load since `c` is not declared anywhere and cannot be
retrieved (since there is no `_ENV` parameter, not even a nil one).

> _ENV is not always guarenteed to be the first upvalue, or even the first table upvalue

This is exactly the problem I started out trying to solve.