pub struct string;Expand description
The type of immutable sequences of bytes.
Strings in Lua can contain any 8-bit value, including embedded zeros,
and are used both for text and for arbitrary binary data. Strings are
immutable: functions like upper return new
strings and never modify their argument.
The string library sets a metatable for strings where the __index
field points to the library itself, so every string function can be
called in object style:
print(string.upper("lua")) --> LUA
print(("lua"):upper()) --> LUAString indices count from 1; negative indices count backwards from the end of the string, so −1 is the last byte.
Implementations§
Source§impl string
§Method form
These functions receive the string as self, so the string
metatable makes them callable in method form: ("lua"):upper()
is the same as string.upper("lua").
impl string
§Method form
These functions receive the string as self, so the string
metatable makes them callable in method form: ("lua"):upper()
is the same as string.upper("lua").
Sourcepub fn byte(&self, i: option<number>, j: option<number>) -> Repeatable<number>
pub fn byte(&self, i: option<number>, j: option<number>) -> Repeatable<number>
Returns the internal numeric codes of characters in a string.
§Parameters
i: position of the first character (default 1).j: position of the last character (defaulti).
§Return value
The internal numeric codes of the characters s[i], s[i+1],
…, s[j], as integers.
§Examples
print(("A"):byte()) --> 65
print(("Lua"):byte(1, 3)) --> 76 117 97
print(("Lua"):byte(-1)) --> 97§See also
Sourcepub fn find(
&self,
pattern: string,
init: option<number>,
plain: option<boolean>,
) -> option<(number, number)>
pub fn find( &self, pattern: string, init: option<number>, plain: option<boolean>, ) -> option<(number, number)>
Finds the first match of a pattern in a string.
§Parameters
pattern: the pattern to search for.init: where to start the search (default 1; may be negative).plain: when true, turns off the pattern matching facilities: a plain “find substring” is performed, with no characters being considered magic.
§Return value
The indices of s where the occurrence starts and ends, or nil
if the pattern is not found. If the pattern has captures, the
captured values are also returned, after the two indices.
§Examples
print(("hello Lua"):find("Lua")) --> 7 9
print(("hello"):find("l+")) --> 3 4
print(("a.b"):find(".", 1, true)) --> 2 2 (plain search)
print(("key=val"):find("(%w+)=(%w+)")) --> 1 7 key val§See also
Sourcepub fn format(&self, values: Repeatable<any>) -> string
pub fn format(&self, values: Repeatable<any>) -> string
Returns a formatted string.
§Parameters
formatstring: a format description following the same rules as the ISO C functionsprintf, plus the extra specifier%q.···: the values to format.
§Return value
The formatted string. The specifier %q formats booleans, nil,
numbers and strings in a way that the result can be safely read
back by the Lua interpreter.
§Examples
print(string.format("%s scored %.1f%%", "Ana", 97.5))
--> Ana scored 97.5%
print(string.format("%5d|%-5d|", 42, 42)) --> 42|42 |
print(string.format("%q", 'he said "hi"')) --> "he said \"hi\""
print(string.format("%x", 255)) --> ffSourcepub fn gmatch(&self, pattern: string, init: option<number>) -> function
pub fn gmatch(&self, pattern: string, init: option<number>) -> function
Returns an iterator over the matches of a pattern in a string.
§Parameters
pattern: the pattern to search for.init: where to start the search (default 1).
§Return value
An iterator function that, each time it is called, returns the
next captures from pattern over s. If the pattern specifies no
captures, the whole match is produced in each call. Anchors (^)
do not work in gmatch, as that would prevent iteration.
§Examples
for word in ("one two three"):gmatch("%a+") do
print(word) --> one / two / three
end
for k, v in ("a=1, b=2"):gmatch("(%w+)=(%w+)") do
print(k, v) --> a 1 / b 2
end§See also
string.match, find
Sourcepub fn gsub(
&self,
pattern: string,
repl: any,
n: option<number>,
) -> (string, number)
pub fn gsub( &self, pattern: string, repl: any, n: option<number>, ) -> (string, number)
Returns a copy of a string with pattern matches replaced.
§Parameters
pattern: the pattern to search for.repl: the replacement — a string (where%1to%9stand for captures and%0for the whole match), a table (queried with the first capture as key), or a function (called with all captures as arguments). A false ornilresult keeps the original match.n: the maximum number of substitutions (default: unlimited).
§Return value
A copy of s with the replacements made, plus the total number
of matches that occurred.
§Examples
print(("hello world"):gsub("o", "0")) --> hell0 w0rld 2
print(("hello world"):gsub("o", "0", 1)) --> hell0 world 1
print(("hello"):gsub("(l+)", "[%1]")) --> he[ll]o 1
print(("2+3"):gsub("%d", function(d)
return d * 10
end)) --> 20+30 2§See also
Sourcepub fn lower(&self) -> string
pub fn lower(&self) -> string
Converts a string to lowercase.
§Return value
A copy of the string with all uppercase letters changed to lowercase; all other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
§Examples
print(("Hello, World!"):lower()) --> hello, world!§See also
Sourcepub fn match(&self, pattern: string, init: option<number>) -> Repeatable<any>
pub fn match(&self, pattern: string, init: option<number>) -> Repeatable<any>
Finds the first match of a pattern and returns its captures.
§Parameters
pattern: the pattern to search for.init: where to start the search (default 1).
§Return value
The captures from the first match of pattern in s; if the
pattern specifies no captures, the whole match is returned.
Returns nil when there is no match.
§Examples
print(("hello 42 world"):match("%d+")) --> 42
print(("key = value"):match("(%w+)%s*=%s*(%w+)")) --> key value
print(("hello"):match("%d+")) --> nil§See also
Sourcepub fn rep(&self, n: number, sep: option<string>) -> string
pub fn rep(&self, n: number, sep: option<string>) -> string
Repeats a string.
§Parameters
n: the number of copies.sep: a separator inserted between copies (default: the empty string).
§Return value
A string that is the concatenation of n copies of s separated
by sep. If n is not positive, the empty string.
§Examples
print(("ab"):rep(3)) --> ababab
print(("ab"):rep(3, "-")) --> ab-ab-ab
print(("ab"):rep(0)) --> (empty string)Sourcepub fn sub(&self, i: number, j: option<number>) -> string
pub fn sub(&self, i: number, j: option<number>) -> string
Extracts a substring.
§Parameters
i: position of the first character. Negative values count from the end of the string.j: position of the last character (default −1, the end of the string).
§Return value
The substring of s that starts at i and continues until j,
inclusive. If i is greater than j (after normalising negative
indices), the empty string.
§Examples
print(("hello"):sub(2, 4)) --> ell
print(("hello"):sub(2)) --> ello
print(("hello"):sub(-3)) --> llo
print(("hello"):sub(2, -2)) --> ellSourcepub fn upper(&self) -> string
pub fn upper(&self) -> string
Converts a string to uppercase.
§Return value
A copy of the string with all lowercase letters changed to uppercase; all other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.
§Examples
print(("Hello, World!"):upper()) --> HELLO, WORLD!§See also
Source§impl string
§Library functions
These functions take no string self and are only reachable
through the library table itself, e.g. string.char(76, 117, 97).
impl string
§Library functions
These functions take no string self and are only reachable
through the library table itself, e.g. string.char(76, 117, 97).
Sourcepub fn char(codes: Repeatable<number>) -> string
pub fn char(codes: Repeatable<number>) -> string
Builds a string from numeric character codes.
§Parameters
···: zero or more integers, one per character.
§Return value
A string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument.
§Examples
print(string.char(76, 117, 97)) --> Lua
print(string.char()) --> (empty string)§See also
Sourcepub fn dump(f: function, strip: option<boolean>) -> string
pub fn dump(f: function, strip: option<boolean>) -> string
Serializes a function into a binary string.
§Parameters
function: a Lua function without upvalues… or with — upvalues are saved only by their number, with fresh ones created on load.strip: when true, the binary may not include debug information (line numbers, local names).
§Return value
A binary string that, passed to load, returns a
copy of the function. Functions defined in C cannot be dumped.
§Examples
local f = function(x) return x * 2 end
local bin = string.dump(f)
local g = load(bin)
print(g(21)) --> 42Sourcepub fn pack(fmt: string, values: Repeatable<any>) -> string
pub fn pack(fmt: string, values: Repeatable<any>) -> string
Serializes values into a binary string.
§Parameters
fmt: a format string describing the layout — e.g."i4"for a 4-byte signed integer,"d"for a double,"z"for a zero-terminated string, with<and>selecting endianness (§6.4.2 of the manual lists all options).v1, v2, ···: the values to serialize.
§Return value
A binary string containing the values packed according to fmt.
§Examples
local bin = string.pack("<i4i4", 1, 2)
print(#bin) --> 8
print(string.unpack("<i4i4", bin)) --> 1 2 9§See also
Sourcepub fn packsize(fmt: string) -> number
pub fn packsize(fmt: string) -> number
Returns the size of a pack format.
§Parameters
fmt: a format string as inpack. It must not contain variable-size options (sorz).
§Return value
The total size in bytes of a string produced by
pack with the given format.
§Examples
print(string.packsize("i4i4")) --> 8
print(string.packsize("dd")) --> 16Sourcepub fn unpack(fmt: string, s: string, pos: option<number>) -> Repeatable<any>
pub fn unpack(fmt: string, s: string, pos: option<number>) -> Repeatable<any>
Deserializes values from a binary string.
§Parameters
fmt: a format string as inpack.s: the binary string to read.pos: where to start reading (default 1).
§Return value
The values packed in s according to fmt, followed by the
index of the first unread byte.
§Examples
local bin = string.pack("i4z", 7, "hi")
print(string.unpack("i4z", bin)) --> 7 hi 8§See also
Source§impl string
§Extended library — feature extended
Functions from extended.lua, inspired by Rust.
They are not part of standard Lua; require("extended") installs
them into the string library, so they also work in method form.
impl string
§Extended library — feature extended
Functions from extended.lua, inspired by Rust.
They are not part of standard Lua; require("extended") installs
them into the string library, so they also work in method form.
Sourcepub fn split(&self, sep: option<string>) -> table
Available on crate feature extended only.
pub fn split(&self, sep: option<string>) -> table
extended only.Splits a string into a sequence of substrings.
Inspired by Rust’s str::split.
§Parameters
sep: the separator, taken as literal text (not a pattern). When absent, splits on runs of whitespace. Must not be empty.
§Return value
A new sequence with the pieces. With an explicit separator, empty fields are kept.
§Examples
print(inspect(("a,b,c"):split(","))) --> { "a", "b", "c" }
print(inspect(("a,,b"):split(","))) --> { "a", "", "b" }
print(inspect((" one two "):split())) --> { "one", "two" }
print(inspect(("a.b"):split("."))) --> { "a", "b" } (literal dot)Sourcepub fn startswith(&self, prefix: string) -> boolean
Available on crate feature extended only.
pub fn startswith(&self, prefix: string) -> boolean
extended only.Tests whether the string starts with a prefix.
Inspired by Rust’s str::starts_with.
§Examples
print(("hello"):startswith("he")) --> true
print(("hello"):startswith("lo")) --> false
print(("hello"):startswith("")) --> true§See also
Sourcepub fn endswith(&self, suffix: string) -> boolean
Available on crate feature extended only.
pub fn endswith(&self, suffix: string) -> boolean
extended only.Tests whether the string ends with a suffix.
Inspired by Rust’s str::ends_with.
§Examples
print(("hello"):endswith("lo")) --> true
print(("hello"):endswith("he")) --> false§See also
Sourcepub fn contains(&self, sub: string) -> boolean
Available on crate feature extended only.
pub fn contains(&self, sub: string) -> boolean
extended only.Tests whether the string contains a substring.
The needle is literal text: ("a.b"):contains(".") asks about a
real dot, with none of find’s pattern-escaping footguns.
Inspired by Rust’s str::contains.
§Examples
print(("hello"):contains("ell")) --> true
print(("a.b"):contains(".")) --> true
print(("hello"):contains("xyz")) --> falseSourcepub fn replace(&self, old: string, new: string, n: option<number>) -> string
Available on crate feature extended only.
pub fn replace(&self, old: string, new: string, n: option<number>) -> string
extended only.Replaces occurrences of a literal substring.
Inspired by Rust’s str::replace & str::replacen.
§Parameters
old: the substring to find — literal, never a pattern.new: the replacement — also literal;%1means two characters, not a capture.n: the maximum number of replacements (default: unlimited).
§Examples
print(("a.b.c"):replace(".", "-")) --> a-b-c
print(("a.b.c"):replace(".", "-", 1)) --> a-b.c
print(("aaa"):replace("a", "%0")) --> %0%0%0Sourcepub fn count(&self, sub: string) -> number
Available on crate feature extended only.
pub fn count(&self, sub: string) -> number
extended only.Counts non-overlapping occurrences of a substring.
§Examples
print(("banana"):count("an")) --> 2
print(("aaaa"):count("aa")) --> 2 (non-overlapping)Sourcepub fn padleft(&self, len: number, char: option<string>) -> string
Available on crate feature extended only.
pub fn padleft(&self, len: number, char: option<string>) -> string
extended only.Sourcepub fn padright(&self, len: number, char: option<string>) -> string
Available on crate feature extended only.
pub fn padright(&self, len: number, char: option<string>) -> string
extended only.Sourcepub fn lines(&self) -> function
Available on crate feature extended only.
pub fn lines(&self) -> function
extended only.Returns an iterator over the lines of the string.
A trailing newline does not produce a final empty line, and a
trailing \r (Windows line endings) is stripped from each line.
Inspired by Rust’s str::lines.
§Examples
for line in ("one\ntwo\r\nthree\n"):lines() do
print(line) --> one / two / three
endSourcepub fn is_alphabetic(&self) -> boolean
Available on crate feature extended only.
pub fn is_alphabetic(&self) -> boolean
extended only.Tests whether the string consists only of letters. False for the empty string.
Inspired by Rust’s char::is_alphabetic.
§Examples
print(("abc"):is_alphabetic()) --> true
print(("ab1"):is_alphabetic()) --> false
print((""):is_alphabetic()) --> falseSourcepub fn is_numerical(&self) -> boolean
Available on crate feature extended only.
pub fn is_numerical(&self) -> boolean
extended only.Tests whether the string consists only of decimal digits. False for the empty string.
Inspired by Rust’s char::is_numeric.
§Examples
print(("123"):is_numerical()) --> true
print(("12.3"):is_numerical()) --> false (the dot is not a digit)Sourcepub fn is_alphanumeric(&self) -> boolean
Available on crate feature extended only.
pub fn is_alphanumeric(&self) -> boolean
extended only.Tests whether the string consists only of letters and digits. False for the empty string.
Inspired by Rust’s char::is_alphanumeric.
§Examples
print(("a1"):is_alphanumeric()) --> true
print(("a_1"):is_alphanumeric()) --> falseSourcepub fn is_upper(&self) -> boolean
Available on crate feature extended only.
pub fn is_upper(&self) -> boolean
extended only.Tests whether the string has at least one letter and no lowercase ones.
Inspired by Rust’s char::is_uppercase.
§Examples
print(("ABC1"):is_upper()) --> true
print(("AbC"):is_upper()) --> false
print(("123"):is_upper()) --> false (no letters at all)Sourcepub fn is_lower(&self) -> boolean
Available on crate feature extended only.
pub fn is_lower(&self) -> boolean
extended only.Tests whether the string has at least one letter and no uppercase ones.
Inspired by Rust’s char::is_lowercase.
§Examples
print(("abc1"):is_lower()) --> true
print(("aBc"):is_lower()) --> falseTrait Implementations§
Source§impl comparison for string
impl comparison for string
Source§impl concatenation for string
impl concatenation for string
Source§impl indexing for string
impl indexing for string
Source§fn __index(&self, key: any) -> any
fn __index(&self, key: any) -> any
t[key]. Invoked when t is not a
table or when key is not present in the table. The metavalue may
be a function (called with t and key) or a table (in which
the access is repeated) — the latter is the basis of inheritance
in Lua. Read more