Lesson 8 of 10
String patterns
- 14 min
- 6 checks
- 3 hints
- Go to task
Goal
The find, match, gmatch and gsub functions
Explanation
The string library has four functions that search with patterns: find returns the position of the first match, match returns what the parentheses captured, gmatch walks through every match in a for loop, and gsub replaces them all. These are the functions you use to read chat commands and server logs.
But Lua patterns aren't regex. Character classes start with %, not \: %d is a digit, %a is an ASCII letter and %s is whitespace, while + means one or more. Parentheses capture what's inside them, ^ at the start of the pattern makes the match begin at the start of the string, and $ at the end makes it finish at the end of the string. There's no |, no {2,3} and no \b.
The characters ^ $ ( ) % . [ ] * + - ? have special meanings, so to match one of them literally, put % before it, as in %^ and %.. match returns strings, so convert numbers with tonumber. And gsub returns two values, the new string and the number of replacements, so wrap the call in parentheses if you want only the string.
Your task
Write parseGive(msg) so it returns the item name and then its count as a number when the message is exactly in the form /give sword 3, and nil for any other message. Then write totalXp(log), which adds up every entry like +25xp in the log, and stripColors(msg), which removes the color codes ^0 to ^9 used in FiveM chat.
Checks
6 checks- parseGive extracts the item and its count as a number
- The count can have more than one digit
- Rejects a message that doesn't start with the command
- Rejects extra words after the command and a count that isn't a number
- totalXp adds up every +Nxp
- stripColors removes the color codes