Strings and the .. Operator

A string is a piece of text. In Lua you can write a string with double quotes or single quotes. Both work the same way:

local greeting = "Hello"
local name = 'Lua'
print(greeting, name)

Output:

Hello	Lua

The quotes must match. If a string starts with ", it must end with ". Having two kinds is handy when the text contains a quote: 'She said "hi"' works without any backslashes.

Joining strings with ..

To join two strings into one, use two dots, ... This is called concatenation:

local message = greeting .. ", " .. name .. "!"
print(message)
print(#message)

Output:

Hello, Lua!
11

.. adds nothing between the pieces. If you want a comma or a space, you must join it in yourself, like the ", " above.

The # operator in front of a string gives its length, the number of characters in it. Hello, Lua! has 11 characters, because the comma, the space and the ! count too.

Strings and numbers

.. also works with numbers. Lua turns the number into text first:

local year = 2024
print("Year: " .. year)
print(#tostring(year))

Output:

Year: 2024
4

tostring turns any value into a string. Here it is needed because # only works on strings. Without it, you get an error:

local year = 2024
print(#year)

Output:

/usr/bin/lua5.4: main.lua:2: attempt to get length of a number value (local 'year')

One more mistake to avoid: in some languages + joins strings. In Lua, + is only for math:

print("Hello" + "World")

Output:

/usr/bin/lua5.4: main.lua:1: attempt to add a 'string' with a 'string'

To join strings, always use ...

Lua has many more string functions, for example to change case or to search inside a string. You will learn them in the Standard Library section.

In the exercise, join a first name and a last name, then print the result and its length.