string

String manipulation of Lua 5.1 / LuaJIT 2.1. Every function is also available as a method on string values: ("abc"):upper(). Indices are 1-based and negative indices count from the end.


Functions

string.byte(s: string, i?: number = 1, j?: number = i): number

string.byte(s: string, i?: number = 1, j?: number = i): number

  • Returns the numeric codes (0 to 255) of the characters s[i] to s[j], as multiple values.
  • Returns nothing if the range is empty.
print(string.byte("ABC", 1, 3))

string.char(...: number): string

string.char(...: number): string

  • Returns a string made of the characters whose codes are the arguments (each 0 to 255).

string.dump(f: function, strip?: boolean): string

string.dump(f: function, strip?: boolean): string

  • Returns a binary string containing the bytecode of Lua function f. With strip, debug information is removed.
  • f must be a Lua function, not a C function.
  • The result cannot be loaded back with load or loadstring in this VM.

string.find(s: string, pattern: string, init?: number = 1, plain?: boolean = false): number, number, ...string

string.find(s: string, pattern: string, init?: number = 1, plain?: boolean = false): number, number, ...string

  • Looks for the first match of pattern in s, starting at init.
  • Returns the start and end indices of the match, followed by any captures. Returns nil if there is no match.
  • With plain set to true, pattern is searched as a plain substring and no pattern matching is done.
print(string.find("hello world", "wor"))
print(string.find("a.b", ".", 1, true))

string.format(fmt: string, ...: any): string

string.format(fmt: string, ...: any): string

  • Returns fmt with each specifier replaced by the next argument formatted accordingly. See the Format section.
  • Errors if there are too few arguments or the argument has the wrong type.
print(string.format("%5.2f|%-5d|%s", 3.14159, 42, "x"))

string.gmatch(s: string, pattern: string): function

string.gmatch(s: string, pattern: string): function

  • Returns an iterator that, on each call, returns the next captures of pattern in s (the whole match if there are no captures).
  • A ^ at the start of the pattern is not an anchor here: it matches a literal ^ character (("<sup>a</sup>b"):gmatch("^%a") yields "^a" then "^b").
for word in string.gmatch("one two three", "%a+") do
    print(word)
end

string.gsub(s: string, pattern: string, repl: string | table | function, n?: number): string, number

string.gsub(s: string, pattern: string, repl: string | table | function, n?: number): string, number

  • Returns a copy of s where matches of pattern are replaced, and the number of matches.
  • If repl is a string, %1 to %9 insert captures, %0 the whole match and %% a literal %.
  • If repl is a table, the first capture (or whole match) is the key.
  • If repl is a function, it is called with the captures and its result is used.
  • A false or nil replacement keeps the original text. n limits the number of replacements.
print(string.gsub("hello world", "o", "0"))
print(string.gsub("$name is $age", "%$(%w+)", { name = "Bob", age = 30 }))

string.len(s: string): number

string.len(s: string): number

  • Returns the length of s in bytes. Embedded zeros are counted.

string.lower(s: string): string

string.lower(s: string): string

  • Returns s with ASCII uppercase letters converted to lowercase.

string.match(s: string, pattern: string, init?: number = 1): string | number

string.match(s: string, pattern: string, init?: number = 1): string | number

  • Returns the captures of the first match of pattern in s, or the whole match if there are no captures. Returns nil if there is no match.
  • A position capture () returns a number.
print(string.match("key=value", "(%w+)=(%w+)"))

string.rep(s: string, n: number): string

string.rep(s: string, n: number): string

  • Returns s repeated n times. Returns an empty string if n is not positive.

string.reverse(s: string): string

string.reverse(s: string): string

  • Returns s with its bytes in reverse order.

string.sub(s: string, i: number, j?: number = -1): string

string.sub(s: string, i: number, j?: number = -1): string

  • Returns the substring from index i to j, both inclusive. Negative indices count from the end.
print(string.sub("hello", 2, -2))

string.upper(s: string): string

string.upper(s: string): string

  • Returns s with ASCII lowercase letters converted to uppercase.

Patterns

A pattern is a sequence of items. A single character class matches one character.

Character classes

Class Matches
. any character
%a letters
%c control characters
%d digits
%l lowercase letters
%p punctuation
%s whitespace
%u uppercase letters
%w alphanumeric characters
%x hexadecimal digits
%A %C %D %L %P %S %U %W %X the complement of the lowercase class
% followed by a non-alphanumeric character that character literally (for example %. or %%)
[set] any character in the set; ranges like a-z and classes like %d are allowed
[^set] any character not in the set

%g does not exist in Lua 5.1.

Repetition

Item Meaning
x* zero or more, as many as possible
x+ one or more, as many as possible
x- zero or more, as few as possible
x? zero or one

Anchors and captures

  • ^ at the start anchors the match to the start of the subject (or to init).
  • $ at the end anchors the match to the end of the subject.
  • (...) defines a capture, numbered by the position of its opening parenthesis. () captures the current position as a number.
  • %b() matches a balanced pair, here parentheses; any two distinct characters can be used (%bxy).
  • %f[set] is a frontier: matches an empty string where the previous character is not in set and the next one is.
  • %1 to %9 match a copy of the corresponding earlier capture (back-reference).
print(string.match("f(a(b)c)d", "%b()"))
print(string.gsub("THE (quick) fox", "%f[%a]%a+", string.lower))
print(string.match("say 'hi' now", "(['\"])(.-)%1"))

Format

Specifiers for string.format have the form %[flags][width][.precision]type. Flags are -, +, space, # and 0.

Specifier Argument and output
%d %i signed integer
%u unsigned integer
%c character with the given code
%x %X integer in hexadecimal, lowercase or uppercase
%o integer in octal
%e %E number in exponent notation, lowercase or uppercase e
%f number in fixed-point notation
%g %G number in the shorter of %e or %f
%q string quoted so that it can be read back by the Lua parser
%s string; other values are converted with tostring
%% a literal %