Overview
TheIVariable interface represents a variable in Lua code. Variables can be local, global, parameters, or iteration variables. The interface provides information about where variables are declared, how they’re used, and which scopes can access them.
Variable Kinds
Loretta recognizes four kinds of variables through theVariableKind enum:
- Local - A local variable declared with
local - Global - A global variable (assigned without
local) - Parameter - A function parameter (including
...andarg) - Iteration - A loop iteration variable (from
forloops)
Properties
Name
Gets the variable’s name.Kind
Gets the kind of this variable.Declaration
Gets the syntax node where this variable is declared. Returnsnull for global variables or implicit variables (like the file’s arg and ...).
ContainingScope
Gets the scope that contains this variable’s declaration.ReadLocations
Gets all locations where this variable is read from.WriteLocations
Gets all locations where this variable is written to (assigned).ReferencingScopes
Gets all scopes that reference this variable.CapturingScopes
Gets all scopes that capture this variable as an upvalue (closures that reference this variable from an outer scope).Methods
CanBeAccessedIn
Returns whether this variable can be accessed in the provided scope.scope- The scope to check access in
trueif the variable can be accessed in the scope,falseotherwise
Finding and Analyzing Variables
Here’s a complete example showing how to find and analyze variables:Detecting Unused Variables
You can use the variable analysis to detect unused variables:Detecting Captured Variables
Detect which variables are captured by closures, which is important for optimization analysis:Analyzing Variable Scope Access
Check which variables are accessible from different scopes:Common Use Cases
Finding All Global Variables
Detecting Variables That Are Never Read
Detecting Single-Assignment Variables (Constants)
Helper Extension Methods
You can create extension methods to make variable analysis easier:See Also
- Script - Entry point for scope analysis
- IScope - Interface for scopes
- VariableKind - Enum for variable kinds