luacheck icon indicating copy to clipboard operation
luacheck copied to clipboard

Using _ENV instead of self

Open surfskidude opened this issue 7 years ago • 5 comments

I use _ENV as first argument to an object oriented Lua library and I get warnings on _ENV not being used and that the variables in the _ENV table are undefined.

Example: local function f1(_ENV) return xyz -- xyz is in the _ENV table end

surfskidude avatar Sep 11 '18 21:09 surfskidude

It's easy enough to treat globals in scope of some local _ENV as its fields, silencing the warnings.

It's a bit trickier with top level "global" _ENV (technically an upvalue of the main chunk). If it's assigned to then it's no longer obvious whether globals point to original global environment, or to the assigned one, or possibly to both.

local function something(t)
    _ENV = t
end

some_function(something)

 -- Warn about unknown field or assume _ENV could have been assigned to by now?
os.unknown_function()

This can be implemented, too (translate each global name to _ENV.name, add a virtual _ENV upvalue to the main chunk, find reaching assignments for local accesses the way luacheck already does, treat indexing of local _ENV as a global if only the original value of the _ENV upvalue reaches it), it's just a bit complicated.

Then there is also an issue with Lua versions that don't have _ENV. Ideally with --std=lua51 or --std=luajit or --std=min this special _ENV treatment should be disabled, but currenty --std only sets allowed globals and nothing else, and no option values are available during checking, they are applied at a later stage instead.

(I'm just listing reasons why this is not trivial to implement, I'm still adding this to TODOs.)

mpeterv avatar Sep 12 '18 15:09 mpeterv

Yes, I do understand that this is not an easy to implement feature.

Thank you for the detailed response and for considering adding this feature request to your TODO list.

surfskidude avatar Sep 13 '18 00:09 surfskidude

Keeping this open until it's implemented.

mpeterv avatar Sep 13 '18 06:09 mpeterv

Any updates on this?

Mehgugs avatar Jan 23 '19 11:01 Mehgugs

@Mehgugs http://lua-users.org/lists/lua-l/2018-11/msg00114.html

linuxmaniac avatar Jan 30 '19 00:01 linuxmaniac