Lua Pattern Matching Tutorial – Complete Guide

Welcome to our comprehensive guide on Lua pattern matching. With Lua, you can create fantastic programs and build fun, interactive games. To elevate your skill level and get the most out of Lua, learning about pattern matching is an absolute must. Not only does it make your coding simpler and cleaner, but it allows you to perform complex tasks with a surprising amount of ease.

What is Lua Pattern Matching?

Before you can master it, you need to understand what Lua pattern matching is. In simple terms, it is a technique used in Lua programming that allows you to find and manipulate specific strings or sequences within larger pieces of data. Think of it as a handy tool that helps you sort through a haystack to find the very needle you’re looking for!

Why is Lua Pattern Matching Important?

Learning Lua pattern matching can drastically enhance your coding efficiency. With it, you can perform complex string operations that would otherwise not be possible or be too cumbersome with traditional methods. For game creators, this could be crucial in creating exciting gameplay elements or mechanics.

Why Should You Learn About it?

As a coder, your goal is to solve problems efficiently; Lua pattern matching allows you to do just that. The ability to manipulate text and data strings effectively is an invaluable skill to have in your coding toolkit. Be it game development, web development, or artificial intelligence, having this skill will take you a long way in your journey.

CTA Small Image




Basic Lua Pattern Matching

We’ll kick things off with some basic pattern matching examples in Lua. Here, we’ll demonstrate the usage of core pattern-matching functions string.match and string.gmatch.

To begin, let’s use the string.match function to locate and retrieve a specified sequence from a string.

str = "Hello Zenva academy"
match = string.match(str, "Zenva")
print(match) -- prints "Zenva"

In the code above, string.match function searches for the word ‘Zenva’ in the given string and retrieves it. Simple as that!

It’s time to move a notch higher. Lua patterns have been invented to match not only exact words but also sequences, repetitions, and much more. See how we can match any four-letter word in the following string:

str = "Halt! Who goes there?"
match = string.match(str, "%a%a%a%a")
print(match) -- prints "Halt"

The magic lies in the ‘%a%a%a%a’. This is a pattern that matches any four-letter word (‘%a’ stands for any letter).

Using string.gmatch

The string.gmatch function works slightly differently but is equally valuable. This function can be used to iterate through a string, finding every occurrence of a given pattern. Here ‘s how:

str = "The quick brown fox jumps over the lazy dog"
for word in string.gmatch(str, "%a+") do

What’s happening here? The loop goes through the entire string and prints every word individually. The pattern ‘%a+’ stands for any sequence of alphabets (a word).

A little tweak to the pattern can bring about a fun result:

for word in string.gmatch(str, "%a%a%a+") do

The modified pattern ‘%a%a%a+’ only matches words of three letters or more, excluding the smaller words.

This is just the tip of the iceberg when it comes to Lua pattern matching. In the next section, we’ll explore some advanced concepts to give you an invincible command over this powerful feature.

Pattern Characters and Modifiers

As you delve deeper into Lua pattern matching, understanding different pattern characters and modifiers makes it even more versatile. Single-letter pattern characters are powerful, but when combined with modifiers, they’re simply unmatched!

Pattern Characters

Unlike regular expressions used in other programming languages, Lua uses its own set of metamethods that can match more than one character at a time. Below are a few common pattern characters:

  • ‘.’ – matches any single character
  • ‘%a’ – matches any letter
  • ‘%d’ – matches any number
  • ‘%w’ – matches alphanumeric characters
  • ‘%s’ – matches any whitespace character

Let’s take a look at some examples using these pattern characters:

str = "Zenva 1234"
print(string.match(str, "%a+")) -- prints "Zenva"
print(string.match(str, "%d+")) -- prints "1234"
print(string.match(str, "%w+")) -- prints "Zenva"
print(string.match(str, "%s")) -- prints " " (a single space)


Modifiers dictate the quantity of repeating pattern characters. Commonly used modifiers in Lua pattern matching are:

  • ‘*’ – 0 or more repetitions
  • ‘+’ – 1 or more repetitions
  • ‘-‘ – 0 or more repetitions (shortest sequence)
  • ‘?’ – 0 or 1 repetition

Now, let’s see these modifiers in action:

str = "123 Hello 4567 Zenva 890"
print(string.match(str, "%d*")) -- prints "123"
print(string.match(str, "%a+")) -- prints "Hello"
print(string.match(str, "%w-")) -- prints "123"
print(string.match(str, "%s?")) -- prints " " (a single space)

Combining Pattern Characters and Modifiers

Combining pattern characters and modifiers offers greater control over pattern matching. By specifying different pattern characters and modifiers, you can manipulate the sequences of letters, numbers, and other characters in countless ways.

For example, here’s how you can retrieve only the numeric sequences from an alphanumeric string:

str = "12abc34def56ghi78"
for number in string.gmatch(str, "%d+") do

We’ve successfully extracted each sequence of numbers from the text, regardless of how it’s structured or what it’s mixed with. Now that’s power!

With Lua pattern matching, the possibilities are as vast as your creativity permits. we hope this guide provides a strong kick-start to resolving complex problems with incredible ease and efficiency.

Custom Sets in Pattern Matching

Pattern matching in Lua is not limited to the default set of pattern characters. You can create custom sets of characters to match in a string. These are known as ‘character classes’ and are defined in square brackets.

The following example shows how to use a custom set to match any vowel in a string:

str = "The quick brown fox jumps over the lazy dog"
for vowel in string.gmatch(str, "[aeiou]") do

This example prints out every lowercase vowel in our sentence.

You can also create custom sets with ranges for numbers and alphabets. Let’s see how to match any lowercase letter between ‘a’ to ‘m’:

for letter in string.gmatch(str, "[a-m]") do

Negating Sets

Adding a caret symbol ‘^’ at the start of your custom set will negate the set. Let’s see an example where we match anything but the numbers:

str = "abc123def456ghi789"
for match in string.gmatch(str, "[^%d]+") do

This example prints out the non-numeric sequences from the string.

Escaping in Lua Patterns

In Lua patterns, certain characters have special meanings. To use these characters literally, you need to escape them using a ‘%’ in front. Here’s how you can match a percentage symbol in a string:

str = "The battery was 100% charged."
match = string.match(str, "%%")
print(match) -- prints "%"

Capturing Matches

Last but not least, let’s discuss capturing in Lua pattern matching. When you want to extract certain parts of a string, you can use parentheses to capture those parts:

str = "The date is 2021-10-06"
date = string.match(str, "%d%d%d%d%-%d%d%-%d%d")
year, month, day = string.match(str, "(%d%d%d%d)%-(%d%d)%-(%d%d)")
print(date) -- prints "2021-10-06"
print(year, month, day) -- prints "2021 10 06"

In the above block, the entire date is captured in the first match. In the second match, individual parts of the date (year, month, day) are captured separately.

Mastering pattern matching in Lua opens up a plethora of possibilities and makes your Lua experience smoother and much more enjoyable. Hopefully, these examples have given you a strong foundation and the confidence to tackle more complex pattern matching scenarios.

Where to Go Next?

Now that you’ve begun your journey into Lua pattern matching, the world is your oyster! But where should you head next on your coding adventure?

We believe our Roblox Game Development Mini-Degree would be an excellent path to continue. This comprehensive course bundle will take you through game creation using Roblox Studio and Lua. From crafting obstacle courses to developing FPS games, you’ll get the hands-on coding practice you need to truly solidify your skills.

The content is ideal for beginners, but there’s plenty to keep more experienced coders hooked too. Available anytime and on any device, these courses help you to fit learning into your lifestyle. At Zenva, it’s our mission to aid you in your learning journey – from beginner to professional.

If you’re after a wider selection of specific topics, feel free to explore our broader collection of Roblox Courses. No matter where you decide to head next, the key is to keep practicing and continue learning. Happy coding!


Pattern matching in Lua is an incredible tool that can make your code simpler and significantly enhance its efficiency. It opens up a vast field of possibilities for string manipulation, powering up your programs and games with less code and effort. Truly, a must-have skill for any serious coder!

Engage in a profound, immersive learning experience with our Roblox Game Development Mini-Degree. Dive deeper into pattern matching, explore the expansive world of Lua, and develop impressive games and applications ready to impress. Join us at Zenva and inspiration will never cease. Happy coding!


Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Unreal, Python, Godot and more.