String manipulation is a crucial aspect of programming in Lua. It allows developers to work with text data efficiently, enabling tasks such as parsing, formatting, and transforming strings.
In Lua, strings can be concatenated using the ..
operator. This is a simple yet powerful way to combine strings:
local greeting = "Hello"
local name = "World"
local message = greeting .. ", " .. name .. "!"
print(message) -- Output: Hello, World!
To find the length of a string, use the #
operator:
local text = "Lua"
print(#text) -- Output: 3
Lua provides a comprehensive string library with various functions for string manipulation. Here are some commonly used functions:
Extract a substring from a given string:
local text = "Lua Programming"
local substring = string.sub(text, 1, 3)
print(substring) -- Output: Lua
Convert strings to uppercase or lowercase:
local text = "Lua"
print(string.upper(text)) -- Output: LUA
print(string.lower(text)) -- Output: lua
Perform global string replacement:
local text = "Lua is cool"
local newText = string.gsub(text, "cool", "awesome")
print(newText) -- Output: Lua is awesome
Lua offers powerful pattern matching capabilities through its string.match()
and string.gmatch()
functions. These functions use Lua's pattern matching syntax, which is similar to regular expressions but with some differences.
Find the first occurrence of a pattern in a string:
local text = "Lua version 5.4"
local version = string.match(text, "%d+%.%d+")
print(version) -- Output: 5.4
Iterate over all occurrences of a pattern in a string:
local text = "apple, banana, cherry"
for fruit in string.gmatch(text, "%w+") do
print(fruit)
end
-- Output:
-- apple
-- banana
-- cherry
string.format()
function for complex string formatting tasks.Mastering string manipulation in Lua is essential for effective text processing and data handling. By combining these techniques with other Lua features like Lua Table Basics and Lua Function Basics, you can create powerful and efficient string-processing algorithms.