More strings
Chapter 2, Working With Lua provided several methods to work with strings. All of these methods where a part of Lua's string library. This section is going to discuss some additional, more advanced methods to deal with strings.
Searching for a substring
Sometimes, you may have a large string (such as the contents of a file) and need to find out if it contains a smaller substring. This can be done with the string.substring
function. This function takes two variables: the large string to search and a smaller string to look for. On success, it returns a number, which is the index at which the substring first appears. On failure, the function returns nil
:
local sentence = "The quick brown fox" local word = "quick" local index = string.find(sentence, word) print ("substring found at index: " .. index)
Note
The second argument is interesting; it doesn't just have to be a string. The second argument to string.substring
can be a pattern, which results in regex like searching. For more info...