Variables & Types
Variables are containers for storing data values. In this lesson, you'll learn how to create and use variables in Lua, understand Lua's 8 basic data types, and master the difference between local and global variables. Lua's dynamic typing makes working with variables simple and flexible!
Creating Variables
In Lua, creating a variable is as simple as assigning a value to a name. Let's start with the basics:
Click Run to execute your code
- Use
localkeyword to create local variables (recommended) - Variable names can contain letters, digits, and underscores
- Variable names must start with a letter or underscore
- Lua is case-sensitive:
nameandNameare different variables
Local vs Global Variables
This is one of the most important concepts in Lua!
| Type | Syntax | Scope | When to Use |
|---|---|---|---|
| Local | local x = 10 |
Current block/function | Almost always (default choice) |
| Global | x = 10 |
Entire program | Rarely (can cause bugs) |
local keyword are
global by default!
This is different from most other languages and a common source of bugs.
Always use
local unless you specifically need a global variable.
-- Good: Local variable
local score = 100
-- Bad: Global variable (avoid!)
score = 100 -- Oops, this is global!
-- Correct way to create multiple local variables
local x, y, z = 1, 2, 3
local
when creating
variables. Your future self (and your teammates) will thank you!
Lua's 8 Basic Types
Lua has 8 basic data types. Let's explore each one:
Click Run to execute your code
Type Descriptions
| Type | Description | Example |
|---|---|---|
nil |
Represents "no value" or "nothing" | local x = nil |
boolean |
True or false values | local flag = true |
number |
Integers and floating-point numbers | local age = 25 |
string |
Text/characters | local name = "Lua" |
function |
Executable code blocks | local f = function() end |
table |
Lua's main data structure | local t = {1, 2, 3} |
userdata |
C data (advanced) | Used for C integration |
thread |
Coroutines (advanced) | For concurrent programming |
Dynamic Typing
Lua is dynamically typed, which means variables don't have fixed typesโthey can hold any type of value and can change types during execution:
local x = 42 -- x is a number
print(type(x)) -- "number"
x = "Hello" -- Now x is a string
print(type(x)) -- "string"
x = true -- Now x is a boolean
print(type(x)) -- "boolean"
type(variable) to check what
type a
variable currently holds. This returns a string like "number",
"string",
"boolean", etc.
Understanding nil
nil is Lua's way of representing "nothing" or "no value". It's used
in several ways:
-- Uninitialized variables are nil
local x
print(x) -- nil
-- Explicitly set to nil
local y = nil
-- Deleting a variable (set to nil)
local z = 100
z = nil -- z is now "deleted"
-- Checking for nil
if x == nil then
print("x has no value")
end
nil to indicate "no value" or
to delete
table entries. It's Lua's way of saying "this doesn't exist" or "this has been
removed."
Truthiness in Lua
In conditional statements, Lua considers only two values as "false":
false(the boolean value)nil(no value)
Everything else is considered "true", including:
if 0 then print("0 is true!") end -- Prints!
if "" then print("Empty string is true!") end -- Prints!
if {} then print("Empty table is true!") end -- Prints!
-- Only these are false:
if false then print("Won't print") end
if nil then print("Won't print") end
0 and
empty strings
are truthy in Lua! Only false and nil
are falsy.
Common Mistakes
1. Forgetting 'local' keyword
Wrong:
count = 0 -- Oops! This is global!
Correct:
local count = 0 -- Local variable
2. Assuming 0 is false
Wrong:
local x = 0
if not x then -- This won't work! 0 is truthy
print("x is zero")
end
Correct:
local x = 0
if x == 0 then -- Explicitly check for 0
print("x is zero")
end
3. Using undefined variables
Wrong:
print(myVariable) -- nil (no error!)
Correct:
local myVariable = "Hello"
print(myVariable) -- "Hello"
Variable Naming Conventions
| Convention | Example | Use Case |
|---|---|---|
| snake_case | user_name |
Standard Lua convention |
| camelCase | userName |
Also common |
| UPPER_CASE | MAX_SIZE |
Constants |
| _private | _internal |
Private/internal variables |
and, break, do, else,
elseif,
end, false, for, function,
if,
in, local, nil, not,
or,
repeat, return, then, true,
until,
while
Exercise: Practice with Variables
Task: Create variables of different types and practice type checking.
Requirements:
- Create at least one variable of each type (nil, boolean, number, string)
- Use the
type()function to check their types - Create a table with your favorite things
- Use
localfor all variables
Click Run to execute your code
Show Solution
-- 1. Create a variable with your name (string)
local myName = "Alice"
-- 2. Create a variable with your age (number)
local myAge = 25
-- 3. Create a variable that says if you like programming (boolean)
local likesProgramming = true
-- 4. Create a table with your favorite things
local favorites = {
color = "blue",
number = 7,
language = "Lua"
}
-- Print everything
print("Name:", myName)
print("Age:", myAge)
print("Likes programming?", likesProgramming)
print("Favorite color:", favorites.color)
print("Favorite number:", favorites.number)
print("Favorite language:", favorites.language)
-- Bonus: Check types
print("\nTypes:")
print("myName is a", type(myName))
print("myAge is a", type(myAge))
print("likesProgramming is a", type(likesProgramming))
print("favorites is a", type(favorites))
Summary
- Variables: Use
localkeyword to create local variables (recommended) - Global vs Local: Variables without
localare global (avoid this!) - 8 Types: nil, boolean, number, string, function, table, userdata, thread
- Dynamic Typing: Variables can change types during execution
- type(): Use
type(x)to check a variable's type - nil: Represents "no value" or undefined
- Truthiness: Only
falseandnilare falsy; everything else is truthy - Naming: Use snake_case or camelCase; avoid reserved keywords
What's Next?
Excellent work! You now understand variables and types in Lua. In the next module, we'll explore Operators & Control Flow, where you'll learn how to perform calculations, compare values, and make decisions in your code. Get ready to make your programs interactive! ๐
Enjoying these tutorials?