Lua Basics
Lua is a lightweight and beginner-friendly programming language. This guide covers the core concepts you need to start writing Lua scripts.
A Lua script is a plain text file with the .lua extension. The script is executed from top to bottom and it can contain a combination of statements, comments, and functions.
You'll learn about:
- Statements
- Comments
- Variables
- Data Types
- Functions
- Flow Control
- Working with Data
The code examples in this guide are meant to teach Lua syntax. Some examples won't run on their own because they're intended as references rather than complete programs.
Statements
A statement is a single instruction that Lua executes.
For example, this statement stores the text "hello" in a variable named greeting.
local greeting = "hello"
Comments
Comments let you leave notes in your code. Lua ignores comments when it runs your script.
Single-line Comments
Use -- for a single-line comment.
-- This comment is ignored by Lua
local greeting = "hello"
Multi-line Comments
Use --[[ and ]] for comments that span multiple lines.
--[[
This is a multi-line comment.
Lua ignores everything between these markers.
]]
local greeting = "hello"
Comments are useful for explaining why your code does something. However, well-named variables and functions often make extra comments unnecessary.
Variables
Variables store values so you can use them later.
local score = 100
local playerName = "John"
Always use local
You can also create a variable without local:
score = 100
However, this creates a global variable.
Global variables are shared across your script (and sometimes other scripts), which can lead to unexpected bugs if multiple scripts use the same name.
They are also slower to access than local variables!
Unless you have a specific reason not to, always declare new variables with local.
Data Types
Lua supports several data types, including:
Numbers
Numbers represent numeric values.
local age = 25
local price = 9.99
Lua uses the same number type for both whole numbers and decimals.
Strings
Strings store text.
They can use either double quotes (") or single quotes (').
local name = "John"
local address = '123 Main St'
Booleans
Booleans represent a value that is either true or false.
local isValid = true
local isCompleted = false
Booleans are commonly used in flow control, such as if statements.
Tables
Tables can be used as:
- Lists (lists of items)
- Dictionaries (key-value pairs)
-- List
local numbers = {1, 2, 3}
-- Dictionary
local player = {
name = "John",
score = 150
}
Nil
Lua uses nil as a kind of non-value, to represent the absence of a useful value or in simpler terms nothingness.
Functions
Functions let you group code into reusable blocks. Instead of writing the same code multiple times, you can place it inside a function and call it whenever you need it.
Creating a Function
Use the function keyword to define a function.
local function sayHello()
-- print is a built-in Lua function.
-- \n starts a new line after the text.
print("Hello!\n")
end
Call the function by writing its name followed by parentheses.
sayHello() -- Output: Hello!
Parameters and Return Values
Functions can accept parameters, which are values passed into the function.
They can also return a value.
local function add(x, y)
return x + y
end
local result = add(5, 10)
print(result .. "\n") -- 15
In this example:
xandyare parameters.5and10are the arguments passed to the function.returnsends the result back to the code that called the function.
Functions as Values
In Lua, functions are values just like numbers and strings. This means you can store them in variables or pass them to other functions.
local myFunction = function()
print("Hello!\n")
end
otherFunction(myFunction)
You won't use this often as a beginner, but it's a powerful feature that makes Lua flexible.
Whenever you find yourself copying and pasting the same code, consider turning it into a function instead.
This practice is known as DRY ("Don't Repeat Yourself") in programming languages.
Flow Control
Flow control determines which code block should run and how many times it runs.
Lua provides several flow control statements:
ifelseifelseforwhilerepeat
If Statements
Use an if statement to run code only when a condition is true.
local x = 5
if x > 10 then
print("x is greater than 10\n")
else
print("x is 10 or less\n")
end
Output:
x is 10 or less
If x > 10 is true, the first block runs. Otherwise, the else block runs instead.
Elseif Statements
Use elseif when you need to check multiple conditions.
local x = 15
if x > 10 then
print("x is greater than 10\n")
elseif x < 0 then
print("x is less than 0\n")
else
print("x is between 0 and 10\n")
end
Output:
x is greater than 10
Lua checks each condition from top to bottom and exits the flow block as soon as one condition is true.
For Loops
A for loop repeats code a set number of times.
for i = 1, 10 do
print(i .. "\n")
end
Output:
1
2
3
...
10
In this example:
istarts at1.iincreases by1after each loop.- The loop stops after
ireaches10.
While Loops
A while loop repeats as long as a condition remains true.
local x = 5
while x > 0 do
print(x .. "\n")
x = x - 1
end
Output:
5
4
3
2
1
If the condition is false before the loop starts, the loop won't run at all.
Repeat Until
A repeat loop is similar to a while loop, except the code runs at least once before the condition is checked.
local x = 5
repeat
x = x - 1
print(x .. "\n")
until x == 0
Output:
4
3
2
1
0
Use repeat when you always want the loop body to execute at least once.
Choose the loop that best matches your situation:
- Use
forwhen you know how many times to loop or if you're iterating through Tables. - Use
whilewhen you don't know how many iterations you'll need. - Use
repeatwhen the code should always run at least once.
Working with Data
Lua provides several built-in functions and operators for manipulating data, such as concatenating strings, performing mathematical operations, and more.
Strings
Use .. to join (concatenate) strings.
local greeting = "Hello, " .. "world!"
print(greeting .. "\n") -- Hello, world!
Math
Lua supports the standard arithmetic operators.
local sum = 2 + 2
local difference = 10 - 5
local product = 2 * 3
local quotient = 10 / 2
These operators work just like they do in most programming languages.
Tables
Index-Value Tables
Read
local fruits = {"Apple", "Banana", "Orange"}
print(fruits[1] .. "\n") -- Apple
Modify
local fruits = {"Apple", "Banana", "Orange"}
fruits[1] = "Pear"
-- fruits = {"Pear", "Banana", "Orange"}
Length
local fruits = {"Apple", "Banana", "Orange"}
print(#fruits .. "\n") -- 3
Add
local fruits = {"Apple", "Banana", "Orange"}
fruits[#fruits+1] = "Pear"
-- fruits = {"Apple", "Banana", "Orange", "Pear"}
Key-Value Tables
Read
local player = {
name = "John",
score = 100
}
print(player.name .. "\n") -- John
print(player["name"] .. "\n") -- John
Modify
local player = {
name = "John",
score = 100
}
player.score = player.score + 50
print(player.score .. "\n") -- 150
Iterating
You'll often want to process every value in a table. Lua provides two common ways to do this: ipairs() and pairs().
Index-Value Tables
Use ipairs() when your table is a list of values with numeric indexes.
local fruits = {"Apple", "Banana", "Orange"}
for index, fruit in ipairs(fruits) do
print(index, fruit)
end
Output:
1 Apple
2 Banana
3 Orange
ipairs() loops through the array in order, starting at index 1 and stopping when it reaches the first missing index.
Key-Value Tables
Use pairs() when your table stores values using named keys.
local player = {
name = "John",
score = 100
}
for key, value in pairs(player) do
print(key, value .. "\n")
end
Output:
name John
score 100
Unlike ipairs(), pairs() does not guarantee the order that items are visited.
Use ipairs() for simple lists of items and pairs() for collections of named values.