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.