Module std.strict
Diagnose uses of undeclared variables.
All variables(including functions!) must be "declared" through a regular
assignment(even assigning nil
will do) in a strict scope before being
used anywhere or assigned to inside a nested scope.
Use the callable returned by this module to interpose a strictness check
proxy table to the given environment. The callable runs setfenv
appropriately in Lua 5.1 interpreters to ensure the semantic equivalence.
Functions
strict (env) | Require variable declarations before use in scope env. |
Tables
strict | Module table. |
Environment Metamethods
env:__index (n) | Detect dereference of undeclared variable. |
env:__len (t) | Proxy len calls. |
env:__newindex (n, v) | Detect assignment to undeclared variable. |
env:__pairs (t) | Proxy pairs calls. |
Module Metamethods
__call (env[, level=1]) | Enforce strict variable declarations in env. |
__index (name) | Lazy loading of strict submodules. |
Functions
- strict (env)
-
Require variable declarations before use in scope env.
Normally the module strict:__call metamethod is all you need, but you can use this method for more complex situations.
Parameters:
- env table lexical environment table
Returns:
-
table
env proxy table with metamethods to enforce strict
declarations
Usage:
local _ENV = setmetatable({}, {__index = _G}) if require 'std._debug'.strict then _ENV = require 'std.strict'.strict(_ENV) end -- ...and for Lua 5.1 compatibility, without triggering undeclared -- variable error: if rawget(_G, 'setfenv') ~= nil then setfenv(1, _ENV) end
Tables
- strict
-
Module table.
Fields:
- version string release version identifier
Environment Metamethods
- env:__index (n)
-
Detect dereference of undeclared variable.
Parameters:
- n string name of the variable being dereferenced
- env:__len (t)
-
Proxy
len
calls.Parameters:
- t table strict table
- env:__newindex (n, v)
-
Detect assignment to undeclared variable.
Parameters:
- n string name of the variable being declared
- v initial value of the variable
- env:__pairs (t)
-
Proxy
pairs
calls.Parameters:
- t table strict table
Module Metamethods
- __call (env[, level=1])
-
Enforce strict variable declarations in env.
Parameters:
- env table lexical environment table
- level
int
stack level for
setfenv
, 1 means
(default 1)set caller's environment
Returns:
-
table
env which must be assigned to
_ENV
Usage:
local _ENV = require 'std.strict'(_G)
- __index (name)
-
Lazy loading of strict submodules.
Don't load everything on initial startup, wait until first attempt
to access a submodule, and then load it on demand.
Parameters:
- name string submodule name
Returns:
-
table or nil
the submodule that was loaded to satisfy the missing
`name`, otherwise `nil` if nothing was found
Usage:
local strict = require 'std.strict' local version = strict.version