TExcelTAD
Home › Lua › Lua Strings

Lua Strings

A string is a sequence of bytes, usually text. Lua strings are immutable: functions that "change" a string return a new one. Strings can hold any bytes, including zeros and UTF-8 encoded characters.

lua · try it yourself
local single = 'single quotes'
local double = "double quotes"
local long = [[long brackets
keep newlines as typed]]

print(single)
print(double)
print(long)
single quotes
double quotes
long brackets
keep newlines as typed

Single and double quotes are identical in Lua. Pick one per project; use the other when the text contains quotes: 'She said "hi"'.

Escape sequences

Escape Meaning
\n newline
\t tab
\\ backslash
\", \' quote characters
\ddd byte with decimal value ddd (\65 is A)
\xhh byte with hex value hh
\u{XXXX} UTF-8 encoding of a Unicode code point
\z skip the following whitespace, including newlines
lua · try it yourself
print("Tab:\tafter tab")
print("Line 1\nLine 2")
print("Quote: \"Lua\" and back\\slash")
print("\65\66\67", "\x41", "\u{263A}")
print("one long \z
       line")
Tab:	after tab
Line 1
Line 2
Quote: "Lua" and back\slash
ABC	A	☺
one long line

Long strings

Text between [[ and ]] is taken literally: escapes are not processed, and a newline right after [[ is skipped. Add equals signs ([==[ … ]==]) when the text contains ]]. Long strings are great for templates, SQL, or embedded code:

lua · try it yourself
local query = [[
SELECT name
FROM users
WHERE id = 7]]
print(query)
print([==[a[b[1]] stays as is, \n too]==])
SELECT name
FROM users
WHERE id = 7
a[b[1]] stays as is, \n too

Concatenation and length

.. joins strings (numbers are converted automatically). # gives the length in bytes:

lua · try it yourself
local first, last = "Ada", "Lovelace"
local full = first .. " " .. last
print(full, #full)
print("Level " .. 3)
print(#"", #"héllo")
Ada Lovelace	12
Level 3
0	6

#"héllo" is 6, not 5, because é takes two bytes in UTF-8. The utf8 library (later lesson) counts characters.

Tip: Concatenating in a loop (s = s .. piece) creates a new string every time, which is slow for thousands of pieces. Collect the pieces in a table and join them once with table.concat.

Strings have methods

Every string shares the string library as its methods, so s:upper() is the same as string.upper(s). The colon passes the string as the first argument:

lua · try it yourself
local word = "Moonlight"
print(word:upper(), string.upper(word))
print(word:len(), word:lower(), word:reverse())
print(word:sub(1, 4), word:sub(-5))
print(("ab"):rep(3))
MOONLIGHT	MOONLIGHT
9	moonlight	thgilnooM
Moon	light
ababab

A literal needs parentheses before the colon: ("ab"):rep(3).

Comparing strings

== compares contents. < and > compare byte by byte, so uppercase letters (A–Z, codes 65–90) sort before lowercase (a–z, 97–122):

lua · try it yourself
print("apple" == "apple", "apple" < "banana")
print("Zebra" < "apple", "10" < "9")
print(("Zebra"):lower() < ("apple"):lower())
true	true
true	true
false

"10" < "9" is true because strings compare character by character and "1" comes before "9". Compare numbers as numbers.

Test yourself

What is #"Lua" .. "!"?

  1. 4
  2. "3!"
  3. An error
  4. 3

What does [[\n]] contain?

  1. A newline
  2. A backslash and the letter n
  3. Nothing
  4. A syntax error

Which operator joins two strings?

  1. +
  2. &
  3. ..
  4. ++