Declaring Variables in Lua
Understand global vs local variables and naming conventions.
Global vs Local Variables
In Lua, variables are global by default. Writing x = 10 without the local keyword creates a global variable accessible from anywhere. Using local x = 10 restricts the variable to the current block and its nested blocks.
Always prefer local for performance and safety. Accessing a local variable is faster than a global because globals require a hash table lookup in the _G table.
x = 100 -- global variable
local y = 200 -- local variable
do
local z = 300 -- block-local
print(x, y, z) -- 100 200 300
end
print(x, y) -- 100 200
print(z) -- nil (out of scope)The local Keyword
The local keyword declares a variable scoped to the nearest enclosing block: a function body, a do...end block, a loop body, or a file chunk. Local variables are created at the line they're declared and cease to exist at the end of their block.
You can declare multiple locals on one line and initialize them simultaneously. Uninitialized locals default to nil.
local a, b, c = 1, 2, 3
print(a, b, c) -- 1 2 3
local d, e = 10 -- e is nil
print(d, e) -- 10 nil
local f -- nil until assigned
f = 42
print(f) -- 42All lessons in this course
- Lua Data Types Overview
- Declaring Variables in Lua
- Arithmetic and Relational Operators
- Type Coercion and Conversion