Strings

5.1 String Literals

local s1 = "double quotes"
local s2 = 'single quotes'
local s3 = "escapes: \n newline, \t tab, \\ backslash, \" quote, \65 (A), \x41 (A), \u{2764} (heart)"
local s4 = [[
Long string: no escapes processed.
Can span lines. A leading newline is skipped.]]
local s5 = [==[ Can contain ]] and [[ inside ]==]
local s6 = "line one \z
            line two (\\z skips the following whitespace)"

5.2 Basic Operations

Strings are immutable. Every modification creates a new string.

Strings are interned (short strings), so equality comparison is fast.

# returns bytes, not characters. For UTF-8, use the utf8 library (Module 15).

local s = "Hello, Lua"
print(#s)                            --> 10 (length in BYTES)
print(s .. "!")                      --> concatenation
print(s:upper(), s:lower())          --> method syntax: s:upper() == string.upper(s)
print(s:sub(1, 5), s:sub(-3))        --> Hello  Lua (1-based, negative from the end)
print(s:len(), s:rep(2, "-"))        --> 10  Hello, Lua-Hello, Lua
print(s:reverse())
print(s:byte(1), string.char(72, 105))   --> 72  Hi
print(s:find("Lua"))                 --> 8  10
print(("x"):rep(3))                  --> xxx (literals need parentheses for method calls)
print(string.format("%-10s|%5d|%8.3f|%x|%q", "name", 42, math.pi, 255, 'say "hi"'))

5.3 Efficient String Building

-- BAD: O(n^2) due to repeated copying
local s = ""
for i = 1, 10000 do s = s .. i .. "," end

-- GOOD: collect parts in a table, then concatenate once
local parts = {}
for i = 1, 10000 do parts[#parts + 1] = tostring(i) end
local result = table.concat(parts, ",")