TExcelTAD
Home › Lua › Lua String Library

Lua String Library

The string table contains Lua's text functions. Because strings use it as their metatable's __index, you normally call them as methods: name:upper() instead of string.upper(name).

lua · try it yourself
local title = "  The Lua Programming Language  "
print("[" .. title .. "]")
print(title:upper())
print(#title, title:len())
[  The Lua Programming Language  ]
  THE LUA PROGRAMMING LANGUAGE  
32	32

Reference

Function Purpose
s:len() length in bytes (same as #s)
s:upper(), s:lower() change case (ASCII letters)
s:sub(i [, j]) substring from byte i to j (negative counts from the end)
s:rep(n [, sep]) repeat n times, optionally with a separator
s:reverse() reverse the bytes
s:byte(i [, j]) numeric codes of the bytes
string.char(...) build a string from byte codes
s:find(pattern [, init [, plain]]) position of a match
s:match(pattern) the matched text or captures
s:gmatch(pattern) iterator over all matches
s:gsub(pattern, repl [, n]) replace matches, returns the new string and the count
s:format(...) string.format with s as the format

The pattern functions (find, match, gmatch, gsub) get their own lesson. Here we use them with plain text.

Substrings with sub

Positions start at 1. Negative positions count from the end: -1 is the last byte.

lua · try it yourself
local file = "report-2026.csv"
print(file:sub(1, 6))     -- first six characters
print(file:sub(8, 11))    -- the year
print(file:sub(-3))       -- last three: the extension
print(file:sub(-100, 3))  -- out-of-range positions are clamped
print(file:sub(5, 2) == "")
report
2026
csv
rep
true

Bytes and characters

lua · try it yourself
print(("A"):byte(), ("ABC"):byte(1, -1))
print(string.char(76, 117, 97))

-- Caesar shift each letter by 1
local shifted = ("hal"):gsub(".", function(c)
  return string.char(c:byte() + 1)
end)
print(shifted)
65	65	66	67
Lua
ibm

The gsub call above returns two values (the new string and the number of replacements); assigning it to one variable keeps just the string.

Finding and replacing plain text

find returns the start and end positions, or nil if not found. Pass true as the fourth argument to search for plain text, so characters such as . or % are not treated as pattern symbols:

lua · try it yourself
local path = "docs/intro.v2.md"
print(path:find("intro"))
print(path:find(".", 1, true))     -- the first literal dot
print(path:find("missing"))

local text = "cats and more cats"
local replaced, count = text:gsub("cats", "dogs")
print(replaced, count)
print((text:gsub("cats", "dogs", 1)))   -- only the first one
6	10
11	11
nil
dogs and more dogs	2
dogs and more cats

The extra parentheses in the last line keep only the first return value.

Trimming and splitting

Lua has no built-in trim or split, but both are short with patterns:

lua · try it yourself
local function trim(s)
  return (s:gsub("^%s+", ""):gsub("%s+
quot;, "")) end local function split(s, sep) local parts = {} for piece in (s .. sep):gmatch("(.-)" .. sep) do parts[#parts + 1] = piece end return parts end print("[" .. trim(" padded ") .. "]") local fields = split("red,green,,blue", ",") print(#fields, table.concat(fields, " | "))
[padded]
4	red | green |  | blue

split keeps empty fields (between ,,), which is what you usually want for CSV-like data. The pattern (.-) means "as few characters as possible", explained in the patterns lesson.

rep with a separator

lua · try it yourself
print(("-"):rep(20))
print(("ha"):rep(3, " "))
print(("?"):rep(4, ", "))
--------------------
ha ha ha
?, ?, ?, ?

Test yourself

What does ("lunar"):sub(2, 4) return?

  1. "una"
  2. "luna"
  3. "nar"
  4. "un"

What does s:sub(-3) return?

  1. The first three bytes
  2. The last three bytes
  3. An error
  4. nil

What does ("a-b-c"):gsub("-", "+") return?

  1. "a+b+c" only
  2. "a+b+c" and 2
  3. 2 only
  4. "a+b-c"