🎓 A1Learner
🔍
0 of 47 lessons completed

Lua String Functions

Lua string functions are ready-made tools in the string library that change or copy text. Each one takes a string and returns a new string.

Change case with upper and lower

string.upper and string.lower change the case of every letter. The original word stays stored as it was.

local word = "Mixed"
print(string.upper(word))
print(string.lower(word))

Repeat text with string.rep

string.rep copies a string a set number of times. A repeated symbol makes a simple border line.

local border = string.rep("=", 12)
print(border)
print("Sale")
print(border)

Take part of a string with string.sub

string.sub returns the characters between two positions. A negative position counts back from the end of the string.

local word = "notebook"
print(string.sub(word, 1, 4))
print(string.sub(word, -4))

Flip a string with string.reverse

string.reverse returns the same characters in the opposite order. It is a quick way to check a word backwards.

print(string.reverse("stop"))
print(string.reverse("Lua"))

Example

local title = "big sale today"
local article = "Fresh bread arrives daily"
print(string.upper(title))
print(string.sub(article, 1, 11))
print(string.rep("-", 11))

Key points

  • String library: a built-in group of text tools whose names start with string followed by a dot.
  • string.upper: a tool that returns a string with every letter changed to uppercase.
  • string.lower: a tool that returns a string with every letter changed to lowercase.
  • string.rep: a tool that returns a string repeated a given number of times.
  • string.sub: a tool that returns part of a string between two positions.
  • string.reverse: a tool that returns a string with its characters in reverse order.

In this example, string.upper turns the title into a loud heading in all capitals. string.sub then takes the first 11 characters of the article as a short preview. The last line repeats a dash 11 times to underline the preview.

Note

these tools return new strings and leave the original string unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does string.rep("go", 3) return?