Variables are fundamental elements in Lua programming. They serve as containers for storing and manipulating data within your scripts.
In Lua, variables are dynamically typed and don't require explicit declaration. Simply assign a value to create a variable:
local age = 25
name = "Alice"
The local
keyword creates a variable with local scope, while omitting it creates a global variable.
Lua variables can have either local or global scope. Local variables are accessible only within their declaring block, while global variables are accessible throughout the entire program.
local x = 10 -- Local variable
y = 20 -- Global variable
function example()
local z = 30 -- Local to the function
print(x, y, z)
end
example() -- Outputs: 10 20 30
print(x, y, z) -- Outputs: 10 20 nil
Lua allows assigning multiple variables in a single line:
local a, b, c = 1, 2, 3
print(a, b, c) -- Outputs: 1 2 3
Unassigned variables in Lua have a default value of nil
. This special value represents the absence of a value.
local uninitializedVar
print(uninitializedVar) -- Outputs: nil
Understanding variables is crucial for mastering Lua. They form the foundation for more complex Lua Data Types and are essential in Lua Function Basics.