← Back to Lua Course | Chapter 3: Strings | Lesson 2 of 7

Length and concatenation

The # operator gives the length in bytes and .. joins strings together.

In this page:

  1. Length and concatenation

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

lua
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
Common Mistakes
  1. Writing 1..2 without spaces, which is read as a malformed number
  2. Using + to join strings
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.