What is the string.find() method in Lua?

Overview

The string.find() method in Lua accepts two string literals and tries to find one in the other.

For example, there is a string A "This is a good day" as the main string and another string B "a good" as the search string. The string.find() method will search string A to find the string B. When found, like in the case stated, the index of the first and last characters of B as found in A will be returned. For this example, the returned value will be [9, 14].

Syntax

string.find(mainString,searchString)

Parameters

  • mainString: This is the string which will be searched in search of another.
  • searchString: This is the string that needs to be found in the mainString.

Return value

The string.find() method returns the starting and ending indices of the searchString in the mainString.

Example

--declare string variables
mainString1 = "Educative shots on Edpresso"
searchString1 = "shots on"
--number strings
A = "23556667"
B = "35"
--find some string in others and display ouput
print(string.find(mainString1,searchString1))
print(string.find(A,B))
print(string.find("Baple man","lm"))
print(string.find("Apple man","le"))

Note: All search string characters must be placed consecutively in the main string for successful searching. For example, in line 13 in the above code, it is nil because l and m are not side-by-side in the main string parameter. In line 14, the l and e that are indeed side-by-side at the end of word Apple are returned.

Explanation

  • Lines 3–4: We declare variables. These are non-number convertible string values.

  • Lines 7–8: We declare more variables. These are number convertible string values.

  • Lines 11–14: We use the string.find() method to find the second string parameter in the first string parameter.