Menu
Coddy logo textTech

string.find()

Part of the Fundamentals section of Coddy's Lua journey — lesson 48 of 90.

The string.find() function is a powerful tool for searching within strings. It allows you to look for a smaller string (called a pattern) inside a larger string and tells you exactly where it was found.

Here's the basic syntax:

string.find(text, pattern)

When string.find() successfully locates the pattern, it returns two numbers: the starting position and the ending position of the match. If the pattern is not found, it returns nil.

Here's a simple example:

local sentence = "The treasure is hidden here"
local start_pos, end_pos = string.find(sentence, "treasure")
print(start_pos, end_pos)  -- outputs: 5 12

In this example, the word "treasure" starts at position 5 and ends at position 12 in the sentence.

challenge icon

Challenge

Easy

Create a secret message detector that searches for a hidden code word within a larger text message. Declare a variable called message and assign it the value "The ancient treasure lies beneath the old oak tree". Use the string.find() function to search for the word "treasure" within the message and store the starting and ending positions in variables called startPos and endPos. Print both position values on separate lines.

Cheat sheet

The string.find() function searches for a pattern within a string and returns the starting and ending positions of the match, or nil if not found.

Basic syntax:

string.find(text, pattern)

Example:

local sentence = "The treasure is hidden here"
local start_pos, end_pos = string.find(sentence, "treasure")
print(start_pos, end_pos)  -- outputs: 5 12

Try it yourself

-- Declare the message variable
local message = "The ancient treasure lies beneath the old oak tree"

-- TODO: Write your code here to find the word "treasure" and store positions

-- Print the positions
print(startPos)
print(endPos)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals