Lua: Variables & Data Types
What you will learn
Lua is dynamically typed. Variables are global by default — this is different from most languages and can cause bugs if you're not careful.
name = "Alice" -- string
age = 25 -- number (all numbers are double)
is_student = true -- boolean
local score = 100 -- local variable (scoped to block)
Global vs local
- Variables without
localare global — accessible everywhere in the program. - Variables with
localexist only within the block where they're declared (function, loop, chunk). Always uselocalunless you explicitly need global scope.
nil — the absence of a value
nil represents "no value." Accessing an undefined variable returns nil, not an error:
print(x) -- nil (not an error!)
local y = nil -- explicit nil assignment
Dynamic typing
Lua has eight basic types, but only a few are commonly used:
| Type | Example | Notes |
|---|---|---|
nil |
nil |
No value |
boolean |
true, false |
Lowercase |
number |
42, 3.14 |
Double-precision, no separate int |
string |
"hello", 'world' |
Immutable |
table |
{1, 2, 3} |
The only data-structure type |
function |
function() end |
First-class functions |
Common mistakes
- Forgetting
localand accidentally creating a global variable inside a function. - Using
nilin a table index —t[nil]is not a valid table access. - Confusing
falsewithnil— both are falsy, butfalseis a value whilenilmeans absent.
Quick check below!