String Basics: Concat and Length
Use .. for concatenation, # for length, and string.rep/reverse.
String Concatenation with ..
Lua uses .. (two dots) for string concatenation. It works with strings and numbers (numbers are converted automatically). Unlike + in many languages, + in Lua is arithmetic only — using + on strings causes an error.
local first = "Hello"
local second = "World"
print(first .. ", " .. second .. "!") -- Hello, World!
-- Numbers auto-converted
local age = 30
print("Age: " .. age) -- Age: 30
-- Bad: print("x" + "y") ERROR: arithmetic on stringLength Operator #
The # operator returns the byte length of a string. For ASCII strings, this equals the character count. For multi-byte UTF-8 strings, # counts bytes, not characters — a UTF-8 emoji counts as 4. Use a UTF-8 library for character-accurate lengths.
print(#"hello") -- 5
print(#"") -- 0
print(#"café") -- 5 (c,a,f,é=2bytes)
local s = "Lua"
for i = 1, #s do
io.write(string.byte(s, i) .. " ")
end
print() -- 76 117 97All lessons in this course
- String Basics: Concat and Length
- Finding and Extracting Substrings
- string.format for Output
- string.gsub and string.gmatch