Strings
Prerequisites: Data types
Creating strings
local single = 'It said "hi"'
local double = "It's here"
local escaped = "Tab:\tNew line:\nEnd"
local long = [[
Line one
Line two with \n not escaped]]
print(single)
print(double)
print(escaped)
print(long)
It said "hi"
It's here
Tab: New line:
End
Line one
Line two with \n not escaped
- Single and double quotes are equivalent — use one to contain the other.
- Escapes:
\nnewline,\ttab,\\backslash,\"quote. [[ ... ]]is a long string: it can span lines and doesn't process escapes. A newline right after[[is skipped. Use[==[ ... ]==]if the text contains]].
Joining and length
local first, last = "Ada", "Lovelace"
local full = first .. " " .. last
print(full)
print(#full)
print("Score: " .. 42)
Ada Lovelace
12
Score: 42
.. concatenates; # gives the length in bytes.
Formatting
local name, age, price = "Ada", 36, 1234.5
print(string.format("%s is %d years old", name, age))
print(string.format("Price: %.2f", price))
print(string.format("[%-6s|%5d]", name, age))
print(string.format("%05.1f%%", 7.5))
print(string.format("%q", 'say "hi"'))
Ada is 36 years old
Price: 1234.50
[Ada | 36]
007.5%
"say \"hi\""
string.format uses C's printf codes: %s string, %d integer, %.2f
two decimals, -6 left-aligned width 6, %% a literal percent sign, and
%q a quoted, escaped string.
Strings are immutable
String functions return new strings; the original never changes.
Building a long string with .. in a loop is slow, because each step
copies the whole string — collect the pieces in a table and use
table.concat instead (see the Table Library lesson).
Unicode
Lua strings are sequences of bytes, so #"héllo" is 6, not 5. The
utf8 library handles UTF-8 text:
local word = "héllo"
print(#word)
print(utf8.len(word))
for _, code in utf8.codes("hé") do
print(code, utf8.char(code))
end
6
5
104 h
233 é