-- Your pet should find and then bring the potion to the hero. -- This new method checks if the word is in the text. pet.wordInText = function(self, text, word) -- Iterate through each character in the text. for i=1, string.len(text) - string.len(word) + 1, 1 do -- For each character in text loop through each character in word. for j=1, #word + 1, 1 do -- Store the shifted index i + j. local shiftedIndex = i + j -- If a character within the shifted index -- isnt equal to the character in word at the index "j": -- Break the loop. -- If j is equal to the position of the last letter in word: -- Then the entire word is in the text. -- Return true. end end -- word was not found in text. Return false. return false end -- Follow the guides directions where to run. local onHear = function(event) -- If "west" is in the phrase, the pet should run left. if pet:wordInText(event.message, "west") then pet:moveXY(pet.pos.x - 28, pet.pos.y) -- If "north" is in the phrase, the pet should run up. elseif pet:wordInText(event.message, "north") then pet:moveXY(pet.pos.x, pet.pos.y + 24) -- Else the pet should try to fetch the potion. else local potion = pet:findNearestByType("potion") if potion then pet:fetch(potion) end end end pet:on("hear", onHear)
In this case we are adding another method to the
pet object, this allows us to call the new function/method from the onHear function. Normally you would be able to create a global function and wouldn’t need to do this, but for the game attaching a function to the
pet object will allow the functions you declare to be called in other functions you declare.