Variables, Scoping & the Auto-Local Engine

Variables store state in PyLua. Unlike standard Lua where omitting local accidentally pollutes the global table, PyLua features a revolutionary Auto-Local compiler engine that guarantees variable safety by default.

1. The Problem with Standard Lua Variables

In traditional Lua 5.1–5.4, any assignment without the local keyword automatically assigns to the global environment table (_ENV):

lua_standard_issue.lua
-- Standard Lua (Dangerous!)
function calculate()
    count = 10  -- BUG: Accidental global variable! Pollutes _G["count"]
end

This has historically been the #1 source of concurrency race conditions, memory leaks, and hard-to-track mutation bugs in Lua codebases.

2. PyLua Auto-Local Scoping

In PyLua, variables declared inside any function, file, or block automatically default to local scope. You never need to pepper your code with redundant local keywords:

auto_local_demo.lua
function computeArea(width, height) {
    area = width * height    -- Automatically a local variable!
    return area
}

computeArea(10, 20)
print(area)  -- Prints: nil (area did not leak into global scope!)

How the Compiler Backend Manages Auto-Local (`lparser_core.c`)

During the syntax parsing phase in src/parser/impl/lparser_core.c, when the parser encounters a variable assignment:

Variable Assignment Expression (e.g., `x = 50`)
                     │
                     ▼
             searchvar() [lparser_core.c]
                     │
         ┌───────────┴───────────┐
         ▼                       ▼
   Variable found?         Variable not found in active scope?
   (already in nactvar)          │
         │                       ▼
   Reuses register     PyLua Auto-Declaration Engine:
                       ├── Calls registerlocalvar(ls, fs, varname)
                       ├── Increments fs->nactvar
                       ├── Assigns virtual register index (ridx)
                       └── Emits OP_MOVE to target register!

This eliminates global table hashtable lookups (OP_SETTABUP) and replaces them with lightning-fast register operations (OP_MOVE), yielding a measurable speed boost in addition to total scoping safety.

3. Explicit Local Attributes: `<const>` & `<close>`

While basic variables are auto-local, PyLua retains the explicit local keyword to support modern variable attributes:

Compile-Time Constant: `<const>`

Declares a variable that cannot be reassigned after its initial definition. Reassigning triggers a compile-time syntax error:

const_variable.lua
local MAX_PLAYERS <const> = 64
MAX_PLAYERS = 128  -- Compile error: attempt to assign to const variable 'MAX_PLAYERS'

To-Be-Closed Resource (RAII): `<close>`

Declares a scope-bound resource. When execution leaves the enclosing block (whether normally, via return, break, or due to an error/exception), PyLua automatically invokes the variable's __close metamethod:

raii_close.lua
function processFile(path) {
    -- The file handle is automatically closed when leaving this block!
    local f <close> = io.open(path, "r")
    data = f:read("*a")
    return #data
}

4. Upvalues & Lexical Closures

When an inner function accesses a variable defined in an outer function, that variable becomes an upvalue:

upvalues_demo.lua
function createCounter(start) {
    count = start  -- Local to createCounter

    return function() {
        count = count + 1  -- Captures 'count' as an upvalue
        return count
    }
}

c1 = createCounter(0)
print(c1())  -- 1
print(c1())  -- 2

Open vs Closed Upvalues in the VM

While createCounter is active on the call stack, the upvalue is open—pointing directly to the stack slot. When createCounter returns and its stack frame is popped, the VM's luaF_close() automatically copies the value into the closure's heap allocated upvalue structure, making it closed.

5. The Global Environment (`_ENV`)

In PyLua, global variables still exist when deliberately needed. All global variables are fields in the environment table stored in the predefined upvalue _ENV:

global_access.lua
-- Explicit global assignment via _G or _ENV:
_G.GlobalServerState = { running = true }

print(_G.GlobalServerState.running)  -- true
print(_ENV["GlobalServerState"].running) -- true