Codectionary / Developer documentation / Lua

Lua lexical _ENV scopes

In Lua 5.2+, free names resolve through the lexically visible _ENV table. A local environment supplies deliberate globals for one scope. This differs from Luau's Lua 5.1-derived environment model.

Syntax

local _ENV = { print = print, label = "demo" }

Examples

Lua lexical _ENV scopes

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local outerPrint = print
do
    local _ENV = {print = outerPrint, label = "isolated"}
    print(label)
    label = "updated"
    print(label)
end
outerPrint("outside")
  1. Output: isolated, updated, outside. Assignment changes the local environment table rather than an outer local.

Best practices

  • Capture dependencies before replacing _ENV. Restricting names alone is not a secure sandbox for hostile code.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading