Skip to main content

string

Struct string 

Source
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())      --> LUA

String 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").

Source

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 (default i).
§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

char

Source

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

string.match, gmatch, gsub

Source

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 function sprintf, 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))             --> ff
Source

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

Source

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 %1 to %9 stand for captures and %0 for the whole match), a table (queried with the first capture as key), or a function (called with all captures as arguments). A false or nil result 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

find, gmatch

Source

pub fn len(&self) -> number

Returns the length of a string.

§Return value

The length of the string in bytes — equivalent to the # operator. Embedded zeros are counted.

§Examples
print(("hello"):len())    --> 5
print(#"hello")           --> 5
print(("a\0b"):len())     --> 3
Source

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

upper

Source

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

find, gmatch

Source

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)
Source

pub fn reverse(&self) -> string

Reverses a string.

§Return value

A string with the bytes of s in reverse order.

§Examples
print(("Lua"):reverse())    --> auL
Source

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))   --> ell
Source

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

lower

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).

Source

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

byte

Source

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))    --> 42
Source

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

unpack, packsize

Source

pub fn packsize(fmt: string) -> number

Returns the size of a pack format.

§Parameters
  • fmt: a format string as in pack. It must not contain variable-size options (s or z).
§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"))     --> 16
Source

pub fn unpack(fmt: string, s: string, pos: option<number>) -> Repeatable<any>

Deserializes values from a binary string.

§Parameters
  • fmt: a format string as in pack.
  • 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

pack, packsize

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.

Source

pub fn split(&self, sep: option<string>) -> table

Available on crate feature 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)
Source

pub fn trim(&self) -> string

Available on crate feature extended only.

Removes leading and trailing whitespace.

Inspired by Rust’s str::trim.

§Examples
print(("  hi \n"):trim())    --> hi
print(("   "):trim())        --> (empty string)
Source

pub fn startswith(&self, prefix: string) -> boolean

Available on crate feature 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

endswith

Source

pub fn endswith(&self, suffix: string) -> boolean

Available on crate feature 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

startswith

Source

pub fn contains(&self, sub: string) -> boolean

Available on crate feature 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"))    --> false
Source

pub fn replace(&self, old: string, new: string, n: option<number>) -> string

Available on crate feature 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; %1 means 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%0
Source

pub fn count(&self, sub: string) -> number

Available on crate feature extended only.

Counts non-overlapping occurrences of a substring.

§Examples
print(("banana"):count("an"))    --> 2
print(("aaaa"):count("aa"))      --> 2   (non-overlapping)
Source

pub fn padleft(&self, len: number, char: option<string>) -> string

Available on crate feature extended only.

Pads the string on the left to a given length.

§Parameters
  • len: the target length. Longer strings are returned unchanged.
  • char: the fill character (default " ").
§Examples
print(("7"):padleft(3))         -->   7
print(("7"):padleft(3, "0"))    --> 007
§See also

padright

Source

pub fn padright(&self, len: number, char: option<string>) -> string

Available on crate feature extended only.

Pads the string on the right to a given length.

§Examples
print(("7"):padright(3, "."))    --> 7..
§See also

padleft

Source

pub fn lines(&self) -> function

Available on crate feature 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
end
Source

pub fn is_alphabetic(&self) -> boolean

Available on crate feature 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())       --> false
Source

pub fn is_numerical(&self) -> boolean

Available on crate feature 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)
Source

pub fn is_alphanumeric(&self) -> boolean

Available on crate feature 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())    --> false
Source

pub fn is_upper(&self) -> boolean

Available on crate feature 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)
Source

pub fn is_lower(&self) -> boolean

Available on crate feature 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())     --> false

Trait Implementations§

Source§

impl comparison for string

Source§

fn __eq(&self, other: any) -> boolean

The equal (==) operation. Only invoked when the values being compared are both tables or both full userdata and they are not primitively equal. The result is always converted to a boolean. Read more
Source§

fn __lt(&self, other: any) -> boolean

The less than (<) operation. Read more
Source§

fn __le(&self, other: any) -> boolean

The less equal (<=) operation. Read more
Source§

impl concatenation for string

Source§

fn __concat(&self, other: any) -> any

The concatenation (..) operation. Invoked whenever an operand is neither a string nor a number. Read more
Source§

impl indexing for string

Source§

fn __index(&self, key: any) -> any

The indexing access operation 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
Source§

fn __newindex(&self, key: any, value: any)

The indexing assignment t[key] = value. Invoked when t is not a table or when key is not present in the table. Like __index, the metavalue may be a function or another table. Read more
Source§

impl length for string

Source§

fn __len(&self) -> number

The length (#) operation. If the value is not a string and its metatable defines __len, that metavalue is called with the value as argument and its result becomes the length. Read more
Source§

impl tostring for string

Source§

fn __tostring(&self) -> string

Invoked by tostring() (and therefore by print) to convert the value to a string. Read more
Source§

fn __name(&self) -> string

A string naming the type of the value, used in error messages and by tostring when __tostring is absent. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.