Strings in Lua
Strings are sequences of characters used to represent text. Lua provides powerful string manipulation capabilities through its built-in string library. Whether you're processing user input, formatting output, or parsing data, understanding strings is essential. Let's explore everything you need to know about working with strings in Lua!
Creating Strings
Lua offers several ways to create strings:
1. Double Quotes
local message = "Hello, World!"
local name = "Alice"
2. Single Quotes
local greeting = 'Hello, Lua!'
local text = 'It\'s a beautiful day' -- Escape single quote
3. Long Strings (Multi-line)
local multiline = [[
This is a
multi-line
string
]]
local code = [[
function hello()
print("Hello!")
end
]]
[[...]] for multi-line text
or when
you need to include quotes without escaping. They're perfect for embedding code
or SQL
queries!
String Operations
Concatenation
Use .. to join strings together:
Click Run to execute your code
String Length
Use the # operator to get string length:
local text = "Hello"
print(#text) -- 5
local empty = ""
print(#empty) -- 0
String Library Functions
Lua's string library provides powerful functions for string manipulation:
| Function | Description | Example |
|---|---|---|
string.upper(s) |
Convert to uppercase | string.upper("hello") → "HELLO" |
string.lower(s) |
Convert to lowercase | string.lower("HELLO") → "hello" |
string.reverse(s) |
Reverse string | string.reverse("abc") → "cba" |
string.len(s) |
Get length | string.len("hello") → 5 |
string.sub(s, i, j) |
Extract substring | string.sub("hello", 1, 3) → "hel" |
string.rep(s, n) |
Repeat string n times | string.rep("*", 5) → "*****" |
Try String Functions
Click Run to execute your code
str:upper() instead of string.upper(str). Both work
the
same!
String Formatting
Use string.format() for formatted output (like C's printf):
-- Format numbers
local price = 19.99
print(string.format("Price: $%.2f", price)) -- Price: $19.99
-- Format strings
local name = "Alice"
local age = 25
print(string.format("Name: %s, Age: %d", name, age))
-- Padding and alignment
print(string.format("%10s", "hello")) -- Right-aligned
print(string.format("%-10s", "hello")) -- Left-aligned
print(string.format("%05d", 42)) -- 00042
| Format | Type | Example |
|---|---|---|
%s |
String | string.format("%s", "hello") |
%d |
Integer | string.format("%d", 42) |
%f |
Float | string.format("%.2f", 3.14159) |
%x |
Hexadecimal | string.format("%x", 255) → "ff" |
Pattern Matching
Lua uses patterns (similar to regular expressions) for searching and replacing:
Common Pattern Functions
string.find(s, pattern)- Find pattern in stringstring.match(s, pattern)- Extract matching partstring.gmatch(s, pattern)- Iterate over matchesstring.gsub(s, pattern, replacement)- Replace pattern
Click Run to execute your code
Pattern Classes
| Pattern | Matches |
|---|---|
%a |
Letters (a-z, A-Z) |
%d |
Digits (0-9) |
%w |
Alphanumeric (letters and digits) |
%s |
Whitespace |
. |
Any character |
+ |
One or more |
* |
Zero or more |
- |
Zero or more (non-greedy) |
% to escape special characters.
Practice Exercise
Try these string manipulation challenges:
Click Run to execute your code
Summary
In this lesson, you learned:
- Creating strings with quotes and long strings
[[...]] - String concatenation with
.. - String library functions:
upper,lower,sub,find, etc. - String formatting with
string.format() - Pattern matching for searching and replacing
- Common pattern classes:
%a,%d,%w,%s
What's Next?
Now that you can work with strings, it's time to learn about control
flow. In the next lesson, we'll explore conditional statements
(if, elseif, else) to make decisions in
your
code. Let's continue! 🚀
Enjoying these tutorials?