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 themainString.
Return value
The string.find() method returns the starting and ending indices of the searchString in the mainString.
Example
--declare string variablesmainString1 = "Educative shots on Edpresso"searchString1 = "shots on"--number stringsA = "23556667"B = "35"--find some string in others and display ouputprint(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
nilbecauselandmare not side-by-side in the main string parameter. In line 14, thelandethat are indeed side-by-side at the end of wordAppleare 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.