Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 32 · Values and Operators

Strings

Learn Lua strings: quote styles, long brackets, escapes, the .. concatenation operator, the # length operator, string.sub, upper, rep, format and immutability.

A Lua string is an immutable sequence of bytes. It can hold text, but it can just as well hold binary data, because Lua does not assume any encoding. That single design choice explains most of the behavior in this lesson: the length operator counts bytes, indexing is done with functions rather than brackets, and "changing" a string always produces a new one.

You will learn the ways to write a string, how to join and measure strings, the most useful functions of the string library, and how string.format builds text from values. Pattern matching with find, match and gsub gets its own lesson, String Patterns. Real Lua stays read-only on this site, and the runnable stand-ins are written in JavaScript.

Writing string literals

Single and double quotes are interchangeable. Pick the one that avoids escaping.

LUA
local a = "It's fine"
local b = 'She said "hi"'
local c = "Line one\nLine two"
local d = "Tab\there"

Common escape sequences are \n (newline), \t (tab), \\ (backslash), \" and \'. You can also write a byte by value, \65 for decimal or \x41 for hex (both give A), and a Unicode code point with \u{20AC} (the euro sign, encoded as UTF-8). A backslash at the end of a line continues the string onto the next line, and \z skips the whitespace that follows it, which helps with long literals.

LUA
print("A\65\x41\u{20AC}")     --> AAA€  (A, A, A and the euro sign)
print("one \z
       two")                    --> one two

Long brackets

Text between [[ and ]] is a long string. It can span lines, and escape sequences are not processed. A newline directly after the opening bracket is skipped, so you can start the text on the next line.

LUA
local poem = [[
Roses are red,
Lua is small.]]
print(poem)

If the text itself contains ]], add equals signs to both brackets: [==[ ... ]==]. The number of equals signs just has to match. Long brackets are the cleanest way to embed SQL, HTML, JSON or a multi-line message.

Concatenation and length

The operator .. joins strings. Numbers are converted automatically, but you need spaces around .. when a number literal is next to it, because 1..2 is a malformed number.

LUA
print("Hello" .. ", " .. "world")   --> Hello, world
print("n = " .. 42)                 --> n = 42
print("pi ~ " .. 3.14)              --> pi ~ 3.14
print(1 .. 2)                       --> 12

.. only accepts strings and numbers. "a" .. nil raises "attempt to concatenate a nil value", which is one of the most common beginner errors. Use tostring(x) when a value might be anything.

The length operator # returns the number of bytes, not characters.

LUA
print(#"hello")      --> 5
print(#"")           --> 0
print(#"héllo")      --> 6   (é takes two bytes in UTF-8)
print(utf8.len("héllo"))   --> 5

For text with accents or non-Latin scripts, the utf8 library counts and iterates over characters: utf8.len, utf8.char, utf8.codepoint and utf8.codes.

What a string is in Lua

Immutable Functions return new strings.
Bytes

counts bytes, not letters.

Join with .. Numbers convert, nil does not.
Long brackets Multi-line text, no escapes.
1 / 2

The string library

All the functions live in the string table, and every string value has that table as its method source. That means string.upper(s) and s:upper() are the same call. The colon form is the one you will see most.

LUA
local s = "Hello, Lua"
print(s:upper())             --> HELLO, LUA
print(s:lower())             --> hello, lua
print(s:len())               --> 10
print(s:reverse())           --> auL ,olleH
print(s:sub(1, 5))           --> Hello
print(s:rep(2, " | "))       --> Hello, Lua | Hello, Lua
print(("ab"):rep(3))         --> ababab
print(s:byte(1))             --> 72
print(string.char(72, 105))  --> Hi

Notice the parentheses around the literal in ("ab"):rep(3): a string literal needs them before a method call.

Substrings with sub

string.sub(s, i, j) returns the characters from position i to j, inclusive and 1-based. Negative numbers count from the end, and j defaults to -1 (the last character). Out-of-range values are clamped instead of raising errors.

LUA
local s = "hello"
print(s:sub(2, 4))     --> ell
print(s:sub(2))        --> ello
print(s:sub(-3))       --> llo
print(s:sub(1, 1))     --> h
print(s:sub(0, 2))     --> he
print(s:sub(4, 100))   --> lo
print(s:sub(4, 2))     -->            (empty string)

Because strings cannot be indexed with s[i], s:sub(i, i) is how you read one character.

Searching

string.find(s, text) returns the start and end positions, or nil when there is no match. By default it treats the second argument as a pattern, so special characters such as . need care. Pass true as the fourth argument to search for plain text.

LUA
print(("hello"):find("l"))             --> 3	3
print(("a.b"):find(".", 1, true))      --> 2	2
print(("hello"):find("xyz"))           --> nil

Strings are immutable

No function changes a string in place. Each one returns a new value and leaves the original alone.

LUA
local name = "ada"
local big = name:upper()
print(name, big)       --> ada	ADA
name = name:sub(1, 1):upper() .. name:sub(2)
print(name)            --> Ada

To "change" a character you build a new string out of the pieces. Comparing two strings with == compares their contents, and it is fast.

If you build a long string with .. in a loop, each step copies everything so far. For large jobs collect the pieces in a table and join them once with table.concat, which The table Library explains.

Formatting with string.format

string.format works like C's printf. The first argument is a format string with placeholders that start with %, and the other arguments fill them in.

Placeholder Meaning Example result
%d integer string.format("%d", 42) gives 42
%5.2f float, width 5, 2 decimals 3.14159 gives 3.14
%05d zero-padded integer 42 gives 00042
%s any value as a string "Lua" gives Lua
%-6s left-aligned in 6 characters "ab" gives ab
%x hexadecimal 255 gives ff
%q a quoted string safe to read back "a\nb" gives a literal with \ and a newline
%% a literal percent sign %
LUA
print(string.format("%s has %d items", "cart", 3))   --> cart has 3 items
print(("%.2f"):format(2 / 3))                        --> 0.67
print(("[%5d]"):format(42))                          --> [   42]
print(("[%-5d]"):format(42))                         --> [42   ]
print(("%d%%"):format(75))                           --> 75%

%d needs a value with an integer representation: %d with 3.0 prints 3, but with 3.5 it raises "number has no integer representation". %s calls tostring, so it accepts tables, nil and booleans too.

Stand-ins you can run

JavaScript strings are immutable too, but they index from 0 and count UTF-16 units. The first stand-in implements Lua's sub rules and a byte-length function so you can see the 1-based and byte-based behavior.

JS sub and # with Lua rules (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in writes a small rep and format, supporting the most common placeholders, so you can try different widths.

JS string.rep and string.format (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is #"héllo" when the file is saved as UTF-8?

    counts bytes. The letter é takes two bytes in UTF-8, so the length is 6. Use utf8.len for characters.

  2. 2. What does ("hello"):sub(-3) return?

    A negative start counts from the end, so -3 begins at the third-last character and runs to the end.
  3. 3. Which expression raises an error?

    The .. operator only accepts strings and numbers. Concatenating nil raises an error.
  4. 4. After local s = "abc"; s:upper(), what is s?

    Strings are immutable. s:upper() returns a new string, and s itself still holds abc unless you assign the result.
  5. 5. What does string.format("[%5d]", 42) produce?

    A width of 5 without the - flag right-aligns the number with spaces on the left.

Summary

  • Strings are immutable byte sequences; use '...', "..." or long brackets [[...]] to write them.
  • .. joins strings and numbers (not nil), and # counts bytes; utf8.len counts characters.
  • s:sub(i, j) is 1-based and inclusive, accepts negative positions and clamps out-of-range values.
  • upper, lower, rep, reverse, byte, char and find return new values; none changes the original.
  • string.format builds text with placeholders such as %d, %5.2f, %s and %05d.

Next: combine values with Operators and Truthiness.