🎓 A1Learner
🔍
0 of 47 lessons completed

Lua String Operations

Lua string operations are ways to join, measure, and write special characters in text. This lesson covers the three tools you will use most often with text.

Join pieces with ..

The .. operator joins values end to end. It also turns a number into text before joining it.

local first = "Mia"
local last = "Chen"
local level = 5
print(first .. " " .. last)
print("Level " .. level)

Count characters with #

Placing # before a string gives its length. The count includes every space.

local word = "banana"
local sentence = "Lua is fun"
print(#word)
print(#sentence)

Write special characters with escapes

An escape starts with a backslash inside a string. Each escape stands for one special character when the text prints.

print("Line one\nLine two")
print("Name\tMia")
print("He said \"hi\"")
print("C:\\games")

Example

local first = "Alex"
local last = "Rivera"
local role = "Guest"
local tag = "Name: " .. first .. " " .. last
print(tag)
print("Role: " .. role)
print(#tag)

Key points

  • Concatenation: joining two or more values into one longer string with the .. operator.
  • Length operator: the # symbol placed before a string to get its character count.
  • Automatic conversion: the .. operator turns a number into text so it can be joined.
  • Escape sequence: a backslash code inside a string that stands for a special character.
  • Newline: the escape \n moves the text after it onto a new line.

In this example, the tag joins the label, the first name, a space, and the last name into one string. The next line joins the role label with the role value. The last line prints the length of the finished tag, which is 17 characters.

Note

the # count includes spaces and punctuation marks.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does this code print? print(#"hello")