Lua - First Program
Overview
Estimated time: 15–20 minutes
In this tutorial, you'll write and run your first Lua programs. We'll start with the classic "Hello, World!" and gradually introduce basic concepts like variables, functions, and user input.
Learning Objectives
- Write and run your first Lua program
- Understand basic Lua syntax
- Learn about the
print
function - Explore variables and basic operations
- Create simple interactive programs
Prerequisites
- Lua installed on your system
- Text editor or IDE ready
- Basic command line knowledge
Hello, World!
Let's start with the traditional first program. Create a file called hello.lua
:
print("Hello, World!")
Run it from the command line:
lua hello.lua
Expected Output:
Hello, World!
Understanding the Code
print()
is a built-in function that outputs text to the console- Strings are enclosed in double quotes
"..."
or single quotes'...'
- Each statement in Lua can end with a semicolon, but it's optional
Multiple Outputs
The print
function can take multiple arguments:
print("Hello", "World", "from", "Lua!")
print("Numbers:", 1, 2, 3)
print("Mixed:", "The answer is", 42)
Expected Output:
Hello World from Lua!
Numbers: 1 2 3
Mixed: The answer is 42
Note that print
separates multiple arguments with tabs.
Working with Variables
Variables in Lua don't need type declarations:
-- This is a comment
local name = "Alice"
local age = 25
local height = 5.6
print("Name:", name)
print("Age:", age)
print("Height:", height, "feet")
Expected Output:
Name: Alice
Age: 25
Height: 5.6 feet
Local vs Global Variables
Always use local
for variable declarations:
-- Good practice: local variables
local x = 10
local y = 20
-- Global variable (avoid unless necessary)
z = 30
print("Local x:", x)
print("Local y:", y)
print("Global z:", z)
Expected Output:
Local x: 10
Local y: 20
Global z: 30
Basic Arithmetic
Lua supports standard arithmetic operations:
local a = 10
local b = 3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor division:", a // b)
print("Modulo:", a % b)
print("Exponentiation:", a ^ b)
Expected Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Floor division: 3
Modulo: 1
Exponentiation: 1000
String Operations
Working with text in Lua:
local first_name = "John"
local last_name = "Doe"
-- String concatenation with ..
local full_name = first_name .. " " .. last_name
print("Full name:", full_name)
-- String length
print("Length of full name:", #full_name)
-- Multiple lines
local message = "This is line 1\n" ..
"This is line 2\n" ..
"This is line 3"
print(message)
Expected Output:
Full name: John Doe
Length of full name: 8
This is line 1
This is line 2
This is line 3
Simple Functions
Creating and using functions:
-- Function definition
local function greet(name)
return "Hello, " .. name .. "!"
end
-- Function call
local message = greet("World")
print(message)
-- Function with multiple parameters
local function add_numbers(x, y)
return x + y
end
local result = add_numbers(5, 7)
print("5 + 7 =", result)
Expected Output:
Hello, World!
5 + 7 = 12
User Input
Creating interactive programs with io.read()
:
print("What's your name?")
local name = io.read()
print("Hello, " .. name .. "!")
print("Enter a number:")
local input = io.read()
local number = tonumber(input)
if number then
print("Your number squared is:", number ^ 2)
else
print("That's not a valid number!")
end
Example Run:
What's your name?
Alice
Hello, Alice!
Enter a number:
5
Your number squared is: 25
Complete Example Program
Let's put it all together in a simple calculator:
-- Simple Calculator
print("=== Simple Lua Calculator ===")
-- Get first number
print("Enter first number:")
local input1 = io.read()
local num1 = tonumber(input1)
-- Get second number
print("Enter second number:")
local input2 = io.read()
local num2 = tonumber(input2)
-- Check if inputs are valid
if not num1 or not num2 then
print("Error: Please enter valid numbers!")
return
end
-- Perform calculations
print("\nResults:")
print(num1 .. " + " .. num2 .. " = " .. (num1 + num2))
print(num1 .. " - " .. num2 .. " = " .. (num1 - num2))
print(num1 .. " * " .. num2 .. " = " .. (num1 * num2))
if num2 ~= 0 then
print(num1 .. " / " .. num2 .. " = " .. (num1 / num2))
else
print("Cannot divide by zero!")
end
print("\nThanks for using the calculator!")
Example Run:
=== Simple Lua Calculator ===
Enter first number:
12
Enter second number:
4
Results:
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3
Thanks for using the calculator!
Running Programs Different Ways
1. As Script Files
lua program.lua
2. Interactive Mode
$ lua
> print("Hello from REPL!")
Hello from REPL!
> x = 5 * 7
> print(x)
35
> os.exit()
3. Loading Files in Interactive Mode
$ lua
> dofile("hello.lua")
Hello, World!
Common Pitfalls
- Forgetting
local
: Always uselocal
for variables to avoid global pollution - String concatenation: Use
..
not+
for joining strings - Input validation: Always check if
tonumber()
returns a valid number - File extension: Lua files should end with
.lua
Checks for Understanding
- What function is used to output text in Lua?
- How do you concatenate strings in Lua?
- What's the difference between
local x = 5
andx = 5
? - How do you get the length of a string?
- What function converts a string to a number?
Show answers
print()
- outputs text to the console- Use the
..
operator, for example:"Hello" .. " World"
local x = 5
creates a local variable,x = 5
creates a global variable- Use the
#
operator, for example:#"hello"
returns 5 tonumber()
- converts a string to a number, returns nil if conversion fails
Exercises
- Write a program that calculates the area of a rectangle using user input
- Create a program that converts temperatures between Celsius and Fahrenheit
- Make a program that asks for your birth year and calculates your age
Next Steps
Great job! You've written your first Lua programs and learned basic syntax. Next, we'll explore comments and code documentation to make your programs more readable and maintainable.