Lua Strings
Lua - Strings
Section titled “Lua - Strings”In Lua, a string is an immutable sequence of bytes. Strings can contain characters, including embedded zeros and control characters. Lua handles strings efficiently and provides a powerful string library for manipulation.
String Literals
Section titled “String Literals”Strings can be defined using single quotes, double quotes, or long brackets for multi-line strings:
- Single quotes:
'Hello Lua' - Double quotes:
"Hello Lua" - Long brackets:
[[A multi-line string example.]]or[=[Another long string with [=[nested brackets]=].]=]
Example of string literals:
local string1 = "Lua"print("String 1 is: " .. string1)
local string2 = 'Tutorial'print("String 2 is: " .. string2)
local string3 = [[A multi-line stringfor Lua.]]print("String 3 is:\n" .. string3)When the above program is run, the output will be:
String 1 is: LuaString 2 is: TutorialString 3 is:A multi-line stringfor Lua.Escape Sequences
Section titled “Escape Sequences”Within strings delimited by single or double quotes, escape sequences can be used to represent special characters. Long bracket strings do not interpret escape sequences (except for a nuanced newline rule at the beginning).
| Escape Sequence | Description |
|---|---|
| \a | Bell (alert) |
| \b | Backspace |
| \f | Form feed |
| \n | Newline |
| \r | Carriage return |
| \t | Horizontal tab |
| \v | Vertical tab |
| \ | Backslash |
| ” | Double quote |
| ’ | Single quote |
| [ | Left square bracket (needed if using [[ inside a pattern, not typically in string literals) |
| ] | Right square bracket (similar to above) |
| \ddd | Character with decimal value ddd (e.g., \065 is ‘A’) |
| \xhh | Character with hexadecimal value hh (e.g., \x41 is ‘A’) |
| \u{XXX} | UTF-8 sequence for Unicode codepoint XXX (Lua 5.3+) |
String Manipulation
Section titled “String Manipulation”Lua’s string library provides a comprehensive set of functions for string manipulation. Remember that strings are immutable; these functions return new strings rather than modifying the original.
| Function Signature | Purpose |
|---|---|
string.upper(s) | Returns a new string with all lowercase letters in s converted to uppercase. |
string.lower(s) | Returns a new string with all uppercase letters in s converted to lowercase. |
string.gsub(s, pattern, replacement [, n]) | Returns a new string where occurrences of pattern in s are replaced by replacement. n optionally limits the number of substitutions. |
string.find(s, pattern [, init [, plain]]) | Returns the start and end indices of the first match of pattern in s (starting search from init). Returns nil if not found. If plain is true, performs a literal search. |
string.reverse(s) | Returns a new string that is the reverse of s. |
string.format(formatstring, ...) | Returns a formatted string, similar to C’s sprintf. |
string.char(...) | Returns a string formed by characters with the given integer ASCII/byte values. |
string.byte(s [, i [, j]]) | Returns the numerical byte codes of characters s[i], s[i+1], …, s[j]. Default for i is 1, default for j is i. |
string.len(s) | Returns the length of string s in bytes. (Same as #s operator). |
string.rep(s, n [, sep]) | Returns a string that is n repetitions of string s, optionally separated by sep (Lua 5.4+ for sep). |
string.sub(s, i [, j]) | Returns the substring of s that starts at index i and continues until index j; i and j can be negative. |
string.match(s, pattern [, init]) | Similar to string.find, but returns the captured substrings from pattern on success, or nil if no match. |
Let’s explore some examples:
Case Manipulation
Section titled “Case Manipulation”local my_string = "Hello Lua World!"print("Uppercase:", string.upper(my_string)) -- HELLO LUA WORLD!print("Lowercase:", string.lower(my_string)) -- hello lua world!Replacing Substrings (string.gsub)
Section titled “Replacing Substrings (string.gsub)”local text = "Lua is fun, Lua is powerful."local new_text = string.gsub(text, "Lua", "LuaLang")print("Replaced text:", new_text) -- LuaLang is fun, LuaLang is powerful.
local replaced_once = string.gsub(text, "Lua", "LuaLang", 1)print("Replaced once:", replaced_once) -- LuaLang is fun, Lua is powerful.Finding Substrings (string.find) and Reversing (string.reverse)
Section titled “Finding Substrings (string.find) and Reversing (string.reverse)”local phrase = "Lua Tutorial"local start_index, end_index = string.find(phrase, "Tutorial")if start_index then print(string.format("Found 'Tutorial' from index %d to %d", start_index, end_index)) -- Found 'Tutorial' from index 5 to 12end
local reversed_phrase = string.reverse(phrase)print("Reversed phrase:", reversed_phrase) -- lairotuT auLFormatting Strings (string.format)
Section titled “Formatting Strings (string.format)”local name = "Alice"local score = 100local average = 95.756
local formatted1 = string.format("Player: %s, Score: %d", name, score)print(formatted1) -- Player: Alice, Score: 100
local formatted2 = string.format("Average: %.2f (rounded)", average)print(formatted2) -- Average: 95.76 (rounded)
local formatted_date = string.format("Date: %02d/%02d/%04d", 5, 7, 2023)print(formatted_date) -- Date: 05/07/2023Character and Byte Representations (string.char, string.byte)
Section titled “Character and Byte Representations (string.char, string.byte)”local char_A = string.char(65) -- ASCII for 'A'print("Character for 65:", char_A) -- Character for 65: A
local str_abc = "abc"local byte_a = string.byte(str_abc, 1) -- Byte value of 'a'local byte_b = string.byte(str_abc, 2)print(string.format("Byte for 'a': %d, Byte for 'b': %d", byte_a, byte_b)) -- Byte for 'a': 97, Byte for 'b': 98
-- Get all bytesfor i = 1, #str_abc do print(string.format("Byte at %d: %d", i, string.byte(str_abc, i)))endLength, Repetition, Concatenation
Section titled “Length, Repetition, Concatenation”local s1 = "Lua"local s2 = "Rocks"
-- Concatenation using .. operatorlocal combined = s1 .. " " .. s2 .. "!"print("Combined string:", combined) -- Combined string: Lua Rocks!
-- Length using # operator or string.len()print("Length of s1:", #s1) -- Length of s1: 3print("Length of combined:", string.len(combined)) -- Length of combined: 10
-- Repetition using string.rep()local repeated_s1 = string.rep(s1, 3)print("Repeated s1:", repeated_s1) -- Repeated s1: LuaLuaLua
-- Repetition with separator (Lua 5.4+)-- local repeated_sep = string.rep(s1, 3, "-")-- print("Repeated with sep:", repeated_sep) -- Lua-Lua-Lua (if Lua 5.4+)Important Note on UTF-8 and String Length:
Lua’s core string library functions (like string.len, #, string.sub) operate on bytes, not characters. If you are working with UTF-8 encoded strings, a single character might span multiple bytes. For example, #"你好" would likely return 6 (3 bytes per character), not 2. Lua 5.3+ includes a utf8 library (utf8.len, utf8.sub, etc.) for correct handling of UTF-8 encoded Unicode strings. Be mindful of this distinction when processing international text.
Further Resources: The official Lua Reference Manual provides detailed descriptions of all string library functions and pattern matching capabilities.