Lua Variables
Lua - Variables
Section titled “Lua - Variables”A variable is a symbolic name given to a memory location that stores a value. In Lua, variables can hold various types of values, including numbers, strings, booleans, functions, and tables. Lua is a dynamically typed language, meaning you don’t need to declare the type of a variable; its type is determined by the value it holds.
Variable names (identifiers) must begin with a letter or an underscore and can be followed by letters, digits, or underscores. Lua is case-sensitive, so myVariable and myvariable are distinct.
Variable Scope
Section titled “Variable Scope”Lua supports two main scopes for variables:
- Global variables: Variables are global by default unless explicitly declared as local. Global variables are accessible from anywhere in the Lua program (or chunk). They are stored in a special table called the environment table (usually
_G). Overuse of global variables is generally discouraged as it can lead to naming conflicts and harder-to-maintain code. - Local variables: Declared using the
localkeyword. Their scope is limited to the block (e.g., function, loop,ifstatement, or file/chunk) where they are declared. Using local variables is a best practice as it improves code readability, avoids unintended modifications, and can be slightly faster due to optimized access. - Table fields: While not a scope in the same sense, variables can also be fields (or members) of a table. Their accessibility depends on the accessibility of the table itself, e.g.,
myTable.myField = 10.
Variable Declaration and Assignment
Section titled “Variable Declaration and Assignment”In Lua, variables are typically created when they are first assigned a value. If you assign a value to a name that hasn’t been declared local, it becomes a global variable. It’s good practice to always use local unless you specifically need a global variable.
-- Global variable (avoid if possible without specific reason)count = 10
-- Local variable (preferred)local name = "Lua User"
-- Multiple assignmentslocal x, y, z = 1, 2, "hello"
-- If the number of values is less than variables, remaining variables get nillocal a, b, c = 10, 20-- a is 10, b is 20, c is nilprint("a=", a, "b=", b, "c=", c)
-- If the number of values is more than variables, extra values are discardedlocal d, e = 100, 200, 300-- d is 100, e is 200 (300 is discarded)print("d=", d, "e=", e)Variables declared local without an initial value are automatically initialized to nil.
local myVar -- myVar is initialized to nilprint("myVar is: ", myVar)Reassigning Variables
Section titled “Reassigning Variables”You can change the value (and thus, implicitly, the type) of a variable by assigning it a new value.
local data = 100 -- data is a numberprint(type(data), data)
data = "Switched to string" -- now data is a stringprint(type(data), data)
data = { key = "value" } -- now data is a tableprint(type(data), data.key)Example: Variable Swapping and Usage
Section titled “Example: Variable Swapping and Usage”This example demonstrates variable declaration, initialization, and a common Lua idiom for swapping variable values.
-- Variable declaration (implicitly initialized to nil if not assigned)local a, b
-- Initializationa = 10b = 30
print("Initial value of a:", a) -- Output: 10print("Initial value of b:", b) -- Output: 30
-- Swapping variables using multiple assignment (idiomatic Lua)b, a = a, b
print("Value of a after swap:", a) -- Output: 30print("Value of b after swap:", b) -- Output: 10
local result = 70.0 / 3.0print("Value of result (float division):", result) -- Output: 23.333333333333Lvalues and Rvalues in Lua
Section titled “Lvalues and Rvalues in Lua”While Lua doesn’t use these terms as strictly as C/C++, the concepts are useful:
- Lvalue (Locator value): An expression that refers to a memory location where a value can be stored (e.g., a variable name like
x, or a table field likemyTable.fieldormyTable[index]). Lvalues can appear on the left-hand side of an assignment. - Rvalue (Right-hand value): An expression that produces a data value. Rvalues can appear on the right-hand side of an assignment. Literals (like
10or"hello") and expressions (likea + b) are typically rvalues.
In Lua, variables and table fields are lvalues:
local g -- lvalueg = 20 -- 20 is an rvalueA literal cannot be an lvalue:
-- 10 = 20 -- This is invalid and would cause a syntax error.Lua’s multiple assignment allows multiple lvalues and rvalues in a single statement:
local x, y -- x and y are lvaluesx, y = 100, 200 -- 100 and 200 are rvalues-- x becomes 100, y becomes 200Common Pitfall: Accidentally creating global variables is easy if you forget local. Linters or strict mode (require "strict" in older Lua, or linters in modern environments) can help catch this.