Extracting a substring

The string.sub function takes three arguments: the string, a start index, and a stop index. The stop index is inclusive. This function will return a substring between the two indices passed. The last argument is optional; if an end index is not provided, string.sub will just return everything to the end of the string:

local sentence = "The quick brown fox"
local word = "quick"

local start = string.find(sentence, word)
start = start + #word + 1

local result = string.sub(sentence, start)
print("Who was quick?")
print ("the " .. result)

All of the functions in the string library are implemented with respect to the : operator. This means that the preceding code could be re-written as follows:

local sentence = "The quick brown fox"
local word = "quick"

local start = sentence:find(word)
start = start + #word + 1

local result = sentence:sub(start)
print("Who was quick?")
print ("the " .. result)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.255.250