Strings in Lua

Strings are sequences of characters used to represent text. Lua provides powerful string manipulation capabilities with built-in functions and pattern matching.

Creating Strings

Lua strings can be created using single quotes, double quotes, or double square brackets:

-- Single quotes
local str1 = 'Hello World'

-- Double quotes
local str2 = "Hello World"

-- Square brackets (for multi-line strings)
local str3 = [[
This is a multi-line string
that can span multiple lines
without any escape characters.
]]

print(str1)
print(str2)
print(str3)

String Concatenation

The .. operator concatenates strings:

local first = "Hello"
local last = "World"
local greeting = first .. " " .. last
print(greeting)  -- Hello World

-- Numbers are converted to strings when concatenated
local age = 25
local message = "I am " .. age .. " years old"
print(message)  -- I am 25 years old

-- Multiple concatenations
local text = "a" .. "b" .. "c" .. "d"
print(text)  -- abcd

String Length

Use the # operator to get string length:

local text = "Hello Lua"
print(#text)  -- 9

local empty = ""
print(#empty)  -- 0

local multiline = [[
Line 1
Line 2
Line 3
]]
print(#multiline)  -- 21 (includes newlines)

Escape Sequences

Use backslashes for special characters:

local text = "Hello\nWorld"      -- Newline
local quote = "He said \"Hi!\""  -- Double quote
local tab = "First\tSecond"       -- Tab
local backslash = "C:\\Users\\John"  -- Backslash

print(text)
print(quote)
print(tab)
print(backslash)

String Manipulation Functions

Common String Operations

local text = "Hello, World!"

-- Convert to uppercase
local upper = string.upper(text)
print(upper)  -- HELLO, WORLD!

-- Convert to lowercase
local lower = string.lower(text)
print(lower)  -- hello, world!

-- Reverse string
local reversed = string.reverse(text)
print(reversed)  -- !dlroW ,olleH

-- Get substring
local sub = string.sub(text, 1, 5)  -- From position 1 to 5
print(sub)  -- Hello

-- Find substring
local pos = string.find(text, "World")
print(pos)  -- 8 (starting position)

-- Replace substring
local replaced = string.gsub(text, "World", "Lua")
print(replaced)  -- Hello, Lua!

String Formatting

-- Format strings (similar to C's printf)
local name = "Alice"
local age = 30
local height = 5.6

local formatted = string.format("Name: %s, Age: %d, Height: %.1f", name, age, height)
print(formatted)  -- Name: Alice, Age: 30, Height: 5.6

-- Number formatting
local pi = 3.14159
print(string.format("%.2f", pi))        -- 3.14
print(string.format("%08d", 42))       -- 00000042
print(string.format("%x", 255))         -- ff (hexadecimal)
print(string.format("%o", 8))           -- 10 (octal)

Pattern Matching (Lua Patterns)

Lua patterns are simpler than regular expressions but still powerful:

Basic Patterns

local text = "The price is $42.50"

-- %d matches any digit
local price = string.match(text, "%d+%.%d+")
print(price)  -- 42.50

-- %a matches any letter
local letters = string.match("abc123", "%a+")
print(letters)  -- abc

-- %s matches whitespace
local words = string.match("hello world", "%S+")
print(words)  -- hello

-- . matches any character
local match = string.match("abc", ".")
print(match)  -- a

Pattern Quantifiers

local text = "Call me at 555-123-4567"

-- + matches one or more
local digits = string.match(text, "%d+")
print(digits)  -- 555

-- * matches zero or more
local pattern = string.match("abc", ".*")
print(pattern)  -- abc

-- ? matches zero or one
local optional = string.match("color", "colou?r")
print(optional)  -- color

Character Classes

local text = "[email protected]"

-- [a-z] matches any lowercase letter
local lowercase = string.match(text, "[a-z]+")
print(lowercase)  -- ser

-- [A-Z] matches any uppercase letter
local uppercase = string.match(text, "[A-Z]")
print(uppercase)  -- U

-- [0-9] matches any digit (same as %d)
local number = string.match(text, "[0-9]+")
print(number)  -- 123

-- ^ at start of character class negates it
local non_digits = string.match(text, "[^0-9]+")
print(non_digits)  -- User

String Iteration

Iterating Over Characters

local text = "hello"

for i = 1, #text do
    local char = string.sub(text, i, i)
    print(i, char)
end

-- Alternative using gmatch
for char in string.gmatch(text, ".") do
    print(char)
end

Splitting Strings

function split_string(str, delimiter)
    local result = {}
    for match in (str .. delimiter):gmatch("(.-)" .. delimiter) do
        table.insert(result, match)
    end
    return result
end

local text = "apple,banana,orange,grape"
local fruits = split_string(text, ",")

for i, fruit in ipairs(fruits) do
    print(i, fruit)
end

Practical Examples

Input Validation

local function is_valid_email(email)
    -- Basic email validation
    local pattern = "^[%w._%+-]+@[%w.-]+%.%a%a%a?$"
    return string.match(email, pattern) ~= nil
end

print(is_valid_email("[email protected]"))     -- true
print(is_valid_email("invalid.email"))         -- false
print(is_valid_email("user@domain"))           -- false

Word Processing

local function count_words(text)
    local count = 0
    for word in string.gmatch(text, "%S+") do
        count = count + 1
    end
    return count
end

local sentence = "The quick brown fox jumps over the lazy dog"
print("Word count:", count_words(sentence))  -- 9

String Cleaning

local function clean_whitespace(text)
    -- Remove leading and trailing whitespace
    local cleaned = string.match(text, "^%s*(.-)%s*$")
    
    -- Replace multiple spaces with single space
    cleaned = string.gsub(cleaned, "%s+", " ")
    
    return cleaned
end

local messy = "   Hello   there   world!   "
local clean = clean_whitespace(messy)
print("'" .. clean .. "'")  -- 'Hello there world!'

URL Parameter Extraction

local function get_url_param(url, param_name)
    local pattern = param_name .. "=([^&]*)"
    return string.match(url, pattern)
end

local url = "https://example.com?name=John&age=30&city=NewYork"
print(get_url_param(url, "name"))  -- John
print(get_url_param(url, "age"))   -- 30
print(get_url_param(url, "city"))  -- NewYork

String Performance Tips

  1. Use string concatenation with table.concat for many operations
  2. Prefer string.format for complex formatting
  3. Cache pattern results when using patterns repeatedly
  4. Use string.match when you need only the first match
  5. Use string.gmatch for iterating over all matches
-- Efficient string building
local parts = {}
for i = 1, 1000 do
    parts[i] = "Part " .. i
end
local result = table.concat(parts, ", ")

Next Steps

Now that you understand strings, learn about modules to organize your code effectively.

For more string details, see the Lua manual.

Last updated on