Length and concatenation
The # operator gives the length in bytes and .. joins strings together.
In this page:
Length and concatenation
The length operator # counts bytes, not characters, so non-ASCII text may count higher than expected. The .. operator concatenates and converts numbers to strings automatically. Building a long string with many .. in a loop is slow, so collect the pieces in a table and use table.concat.
Note:
Use utf8.len(s) to count characters in UTF-8 text.
Example: Length and concatenation
local s = "Lua"
print(#s, #"", s .. " " .. 5.3)
print(1 .. 2)
print(#"héllo", utf8.len("héllo"))
local parts = {}
for i = 1, 5 do parts[#parts + 1] = i end
print(table.concat(parts, "-"))
-- Output:
-- 3 0 Lua 5.3
-- 12
-- 6 5
-- 1-2-3-4-5
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing 1..2 without spaces, which is read as a malformed number
- Using + to join strings
- Assuming # counts characters in UTF-8 text
Chapter Summary
- #s is the length in bytes
- .. concatenates
- Numbers are converted by ..
- table.concat is better for many pieces
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: