0Pricing
Lua Academy · Lesson

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 string

Length 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 97

All lessons in this course

  1. String Basics: Concat and Length
  2. Finding and Extracting Substrings
  3. string.format for Output
  4. string.gsub and string.gmatch
← Back to Lua Academy