Lua’s string functions are provided by the built-in string library: use functions such as string.sub to extract text, string.find to locate a pattern, and string.gsub to replace matches. Lua strings are immutable byte sequences, so the standard functions work with bytes rather than automatically treating text as Unicode characters.
What the Lua string library does
The string library supplies tools for creating, examining, searching, transforming, and formatting strings. It is part of standard Lua, so ordinary programs do not need to install a separate package to use functions such as string.len or string.match. In standard Lua, functions can also be called with method-style syntax: text:sub(2, 4) is equivalent to string.sub(text, 2, 4). The colon passes the value before it as the first argument.
That syntax is convenient, but it does not mean strings are objects that change in place. Lua strings are immutable: a function that changes capitalization or replaces part of a string returns a new string. Assign the result if you want to keep it.
text = text:lower()stores a lowercase copy.text:gsub('cat', 'dog')returns a replacement string; it does not overwritetext.#textandstring.len(text)both report the string’s byte length.
These basics apply across common Lua versions, though a few library features and details differ by version. Check the documentation for the Lua version embedded in an application or game if a function is unavailable.
Everyday functions for changing strings
Several functions cover routine operations. string.lower(s) and string.upper(s) return lowercase and uppercase copies. Their behavior for letters outside basic ASCII can depend on the current locale; they are not general Unicode case-conversion tools. string.reverse(s) returns the bytes in reverse order, which is useful for ASCII text but can break multibyte UTF-8 characters.
string.rep(s, n) repeats a string n times. In Lua 5.3 and later, an optional separator can be supplied as a third argument. For example, string.rep('ha', 3, '-') produces ha-ha-ha. Older versions may not support that separator argument. string.format, covered below, builds a string from values, while concatenation uses the .. operator: 'hello' .. ' ' .. 'Lua' produces hello Lua.
Choose the operation that describes the job rather than converting everything through patterns. For a fixed piece of text, concatenation is often clearer than a replacement pattern; for repetition, string.rep states the intent directly.
Finding, matching, and extracting text
string.find(s, pattern) searches for a Lua pattern and returns the start and end positions of the first match. Positions are one-based byte positions. If the pattern contains captures, their values are returned after the positions. If there is no match, the function returns nil. For a literal search, pass true as the fourth argument to disable pattern interpretation: string.find('a.b', '.', 1, true) finds the period itself.
string.match(s, pattern) returns the first match, or the captured values if the pattern defines captures. For example, string.match('user@example.com', '([^@]+)@([^@]+)') returns user and example.com. Captures are the parenthesized parts of the pattern. This example separates the text on either side of an at sign; it is not a complete email-address validator.
string.sub(s, i, j) extracts a range of bytes, including both endpoints. Its indexes can be negative, counting backward from the end. Thus string.sub('abcdef', 2, 4) returns bcd, and string.sub('abcdef', -3) returns def. An omitted final index means the end of the string.
Use string.gmatch(s, pattern) when you want to iterate over repeated matches. It returns an iterator, so a loop can process matches one at a time:
for word in string.gmatch('red green blue', '%a+') do
print(word)
end
This prints red, green, and blue on separate lines. If the pattern contains captures, the iterator yields those captured values instead of the full match.
Lua patterns are not regular expressions
Lua has a compact pattern-matching system, but it is not a full regular-expression engine. Common pattern items include . for any character, %d for a digit, %a for a letter, %s for whitespace, and %w for an alphanumeric character. Uppercase forms such as %D and %S match the corresponding complement. Character classes and repetition modifiers let you describe many practical searches.
For instance, '%d+' matches one or more digits, and '%a*' matches zero or more letters. A percent sign introduces classes and escapes pattern punctuation; it is not interchangeable with the backslash conventions used in many regex tools. Lua patterns do not provide the familiar regex alternation operator |, nor do parentheses act as general grouping for alternation. Parentheses are used for captures.
Anchors can constrain a match: ^ marks the beginning and $ the end. For example, string.match('42', '^%d+$') returns 42 only when the entire string consists of digits. A frequent mistake is to assume this makes Lua patterns equivalent to regex; when a pattern needs unsupported features, use explicit Lua logic or a suitable external library instead.
Replacing text with string.gsub
string.gsub(s, pattern, replacement) returns a new string in which matches are replaced. It also returns a second value: the number of replacements. By default it replaces every match; an optional fourth argument limits the number. For example, string.gsub('cat 12', '%d+', '[%0]') returns cat [12] and the count 1. In a replacement string, %0 refers to the whole match, %1 through %9 refer to captures, and %% represents a literal percent sign.
The replacement can also be a function or a table, which is useful when the replacement depends on the matched value. For example, string.gsub('score 7', '%d+', function(n) return tostring(tonumber(n) + 1) end) returns score 8. The callback receives captures when the pattern has them, or the entire match when it does not. Because gsub returns both the changed string and a count, capture the first result when assigning it: text = text:gsub('old', 'new').
Formatting values into text
string.format(format, ...) creates a formatted string using conversion markers similar to those in C’s printf. Common markers include %s for a string, %d for an integer, and %f for a number written in fixed-point form. For example, string.format('Level %d: %s', 3, 'ready') returns Level 3: ready. Width and precision can be specified, as in string.format('%.2f', 3.14159), which returns 3.14.
Match each marker to a suitable value and consult the version’s reference for supported conversions. The %q conversion formats a string so it can be represented as a quoted Lua string. Formatting is useful for consistent output and logs, but concatenation can be simpler when there are only a few values and no formatting requirements.
Bytes, Unicode, and string length
Lua strings store bytes and do not carry an encoding label. Consequently, #s, string.len(s), string.sub, and the positions from string.find count bytes. For plain English text this often matches the number of visible characters. It does not necessarily do so for UTF-8: a single visible character can use multiple bytes, and some displayed characters are made from more than one Unicode code point.
Lua 5.3 and later include the utf8 library for basic UTF-8 operations. utf8.len(s) counts UTF-8 code points and returns nil plus a position if it encounters an invalid sequence. utf8.codes(s) iterates through code points, and utf8.offset helps locate a byte position for a code point. These functions do not provide every Unicode feature: for example, code points are not always the same as user-perceived characters, and the standard library does not supply general Unicode normalization or full case folding.
When slicing or measuring user-visible text, decide whether the task needs bytes, code points, or grapheme clusters. A byte-based substring can cut through a UTF-8 character. If the application handles international text, use the right UTF-8-aware logic or a library designed for the specific Unicode operation.
Choosing a function and avoiding common mistakes
Start with the simplest operation that fits the input. Use string.find for a location, string.match for a result or captures, string.gmatch for repeated matches, and string.gsub for replacements. Use the plain-search option of find when the search term comes from a user and must be treated literally; otherwise characters such as . and % may have pattern meanings.
- Remember that positions and lengths are byte-based unless you explicitly use UTF-8 functions.
- Keep the result of transformations; string functions do not modify their input.
- Account for multiple return values from
findandgsub, especially when assigning results or returning them from a function. - Do not assume Lua patterns support features from JavaScript, Python, or PCRE regular expressions.
- Check the Lua version before relying on newer features such as the
utf8library orstring.pack.
For repeated concatenation in a large loop, building a table of pieces and joining it with table.concat can be a useful approach. It makes the intended assembly explicit and avoids repeatedly constructing a longer intermediate string. For small, straightforward combinations, the .. operator remains readable and appropriate.
Version notes and related functions
Most everyday functions described here are longstanding parts of Lua’s string library. Lua 5.3 added the standard utf8 library and binary-data functions such as string.pack, string.unpack, and string.packsize. Those binary functions are for encoding and decoding structured byte data, not for ordinary text formatting. Some embeddable environments modify or restrict standard libraries, so a function documented for a Lua release may still be unavailable in a host application.
Lua also exposes string functions as methods through its string metatable in standard configurations. Method syntax is shorthand, not a separate family of operations: s:find('x') passes s as the first argument to string.find. If code is difficult to read, the explicit form can make argument order clearer. In either style, check whether a function returns one value or several before using it in an assignment.
Frequently Asked Questions
How do you get the length of a string in Lua?
Use #s or string.len(s). Both return the number of bytes, which may differ from the number of UTF-8 characters.
How do you check whether a string contains text in Lua?
Use string.find(s, pattern) and test whether its first return value is non-nil. Pass true as the fourth argument when the search term must be literal rather than a Lua pattern.
Does Lua have a trim function?
The standard string library does not include a dedicated trim function. Trimming can be implemented with a carefully chosen pattern or supplied by a library; account for the fact that Lua patterns and whitespace rules may not cover every Unicode space character.
Are Lua string functions case-sensitive?
Searches and matches are case-sensitive by default. For basic case conversion, use string.lower or string.upper on copies, while keeping in mind their locale limitations and lack of full Unicode case handling.
Why does string.sub return unexpected results with accented text?string.sub indexes bytes, not visible characters. In UTF-8 text, an accented character may occupy multiple bytes, so byte indexes can split a character. Use UTF-8-aware code when the operation must follow character boundaries.
Related
- How to Split an Activity in P6: Step-by-Step Guide
- JavaScript String Operations: Methods and Examples
- SQL Split Part: Extract a Value by Position
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Filter Excel by Date: Steps, Custom Ranges, and FixesTo filter dates in Excel for Microsoft 365 on Windows, select a cell in your data, choose Data…
- Excel Round to Nearest Quarter Dollar: 3 Easy WaysTo round a price to the nearest quarter dollar in Excel, use =MROUND(A1, 0.25) for standard rounding, =CEILING(A1,…
- Find Years of Service in Excel with a Simple FormulaTo calculate completed years of service in Excel, put each employee’s hire date in B2 and enter =DATEDIF(B2,TODAY(),"y")…
- Excel Formula for the Tab Name: Get the Worksheet NameYes. In Excel for Microsoft 365 on Windows, enter =MID(CELL("filename",A1),FIND("]",CELL("filename",A1))+1,255) in a cell on the worksheet whose name…
- Conditional Formatting If a Cell Is Blank in ExcelTo highlight blank cells in Excel for Microsoft 365 on Windows, select the cells, choose Home > Conditional…
- Average in Excel Without Zeros: Formula and ExamplesTo average numbers in Excel while ignoring zeros, use =AVERAGEIF(A2:A8,"<>0"). Replace A2:A8 with your data range; Excel averages…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.