The _ENV Model in Lua 5.2+
Understand how _ENV replaced setfenv and enables environment control.
What Is _ENV?
In Lua 5.2+, every chunk has an implicit upvalue called _ENV. All global variable accesses are rewritten as field accesses on _ENV. So print(x) becomes _ENV.print(_ENV.x).
_ENV Replaces setfenv
In Lua 5.1, setfenv(fn, env) changed a function's global environment. In 5.2+, this is gone. Instead, set _ENV as a local to change the environment of a chunk or block.
All lessons in this course
- The _ENV Model in Lua 5.2+
- Building a Restricted Sandbox
- Preventing Sandbox Escapes
- Resource Limits and Instrumentation