Lua While Loop Tutorial – Complete Guide

Welcome to our deep dive into the world of Lua, focusing particularly on the ‘while’ loop. By the end of this tutorial, whether you are at the start of your coding journey or an experienced coder looking for a refresher, you will gain a comprehensive understanding of the ‘while’ loop in Lua and its role in game development.

What is a Lua ‘while’ Loop?

A ‘while’ loop in Lua is a control flow statement which allows us to run a piece of code multiple times. It’s called a ‘while’ loop because the code will keep running while a certain condition is true.

What is it useful for?

‘While’ loops are very useful for repetitive tasks, such as checking player input, updating game entities, and iterating over data structures. In game development, ‘while’ loops are bread and butter – they help a game to respond to inputs and change over time.

Why should I learn it?

Understanding ‘while’ loops in Lua is fundamental to becoming proficient at game development. Not only does it allow for astonishing game mechanics, it also makes your code more efficient, cleaner, and easier to debug. If you’re excited about creating your own games, or simply enhancing your programming skills, mastering the ‘while’ loop is big step forward.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Structure of a ‘while’ Loop in Lua

Let’s first look at a simple ‘while’ loop. In this example, we have a variable ‘z’ set to 1. The while loop condition says, “while z is less than or equal to 5, print the variable, and then increment the variable by one.”

z = 1
while z <= 5 do
    print(z)
    z = z + 1
end

This will print out to the console:

1
2
3
4
5

Using ‘while’ Loop with a Table

Another common use of ‘while’ loops is in pairing with Lua tables. Let’s break down an example. Here, we declare a table with 5 elements, setup a ‘while’ loop to print out each item from table until we reach the end.

myTable = { "Apple", "Banana", "Grape", "Orange", "Peach" }
i = 1
while i <= #myTable do
    print(myTable[i])
    i = i + 1
end

This will print the elements of the table:

Apple
Banana
Grape
Orange
Peach

Skipping an Iteration with ‘while’ Loop

You can also skip an iteration in a ‘while’ loop using ‘if’ and ‘then’. Let’s take a look at how we can accomplish this. In the following example, we tell Lua to print the numbers 1 to 5, but we also add an exception for 3.

z = 1
while z <= 5 do
   if z == 3 then
      z = z + 1
      goto continue
   end
   print(z)
   ::continue::
   z = z + 1
end

This will then print:

1
2
4
5

Note here that ‘continue’ is not an actual keyword in Lua. Rather it’s one way to simulate the “continue” behavior from other languages, by using ‘goto’.

‘while’ Loop with Break Statement

A ‘break’ statement inside a ‘while’ loop allows an immediate exit out of the loop. Let’s see a quick example of this below, where we stop looping if the counter reaches 3:

counter = 1
while counter <= 5 do
    if counter == 3 then
        break
    end
    print(counter)
    counter = counter + 1
end

This ‘while’ loop will output:

1
2

The loop breaks once the counter reaches 3, which is why we only see 1 and 2 printed out.

Nested ‘while’ Loops in Lua

We can also incorporate loops inside of already existing loops. By doing so, each iteration of the outer loop triggers the inner loop to run fully. Here’s a basic nested ‘while’ loop example:

outerCounter = 1
while outerCounter <= 3 do
    innerCounter = 1
    while innerCounter <= 3 do
        print("Outer: " .. outerCounter .. " Inner: " .. innerCounter)
        innerCounter = innerCounter + 1
    end
    outerCounter = outerCounter + 1
end

The output of the above piece of code will be:

Outer: 1 Inner: 1
Outer: 1 Inner: 2
Outer: 1 Inner: 3
Outer: 2 Inner: 1
Outer: 2 Inner: 2
Outer: 2 Inner: 3
Outer: 3 Inner: 1
Outer: 3 Inner: 2
Outer: 3 Inner: 3

This clearly demonstrates the function of nested ‘while’ loops. For every one loop of the outer ‘while’ loop, the inner ‘while’ loop runs three times.

Infinite ‘while’ Loops

An important situation to be aware of is the infinite loop. This will cause your program to hang. Therefore, it’s wise to have conditions that will eventually become false and terminate the loop.

Here is an example of an infinite loop:

x = 1
while x > 0 do
    print("This will run forever")
end

The condition for this ‘while’ loop will always be true, and as a result, the content within the loop, “This will run forever”, will print to the console continuously until the program is forcibly stopped.

Mastery of the ‘while’ loop in Lua is essential and we hope that this journey through its various aspects has been valuable. Our aim is to empower learners with the knowledge and skills necessary to feel confident in their coding abilities and ready to take on their next challenge.

Incorporating ‘while’ Loops into Functions

‘while’ loops can also be placed within functions for great utility. We will look at a simple example that uses recursion to print Fibonacci sequence up to a defined count:

function fibonacci(n)
    local a, b = 0, 1
    while n > 0 do
        a, b = b, a + b
        print(a)
        n = n - 1
    end
end
fibonacci(5)

This function will output the first five numbers in the Fibonacci sequence:

1
1
2
3
5

‘while’ Loop and Error Handling

In this example, we’ll use a ‘while’ loop to automatically retry up to a certain number of times if an error is encountered when calling a function:

attemptCount = 0
success = false
while not success and attemptCount < 3 do
    try
    {
        function()
            print("Attempting operation...")
            -- Operation that can fail goes here
        end,
        catch
        {
            function(error)
                attemptCount = attemptCount + 1
                print("There was an error: " .. error)
                print("Retrying... (" .. attemptCount .. " of 3)")
           end
        }
    }
end

This code will try an operation up to 3 times before terminating, printing out errors as it encounters them.

‘while’ Loops for Interactive Input

You can also use a ‘while’ loop for encouraging interaction with your users. Here’s a simple example where the loop waits for the correct password:

print("What's the secret password?")
password = io.read()
while password ~= "letmein" do
    print("That's not the secret password. Try again.")
    password = io.read()
end
print("Correct! Access granted.")

This code waits for the user to enter “letmein” before granting access, continually prompting them to try again if they get it wrong.

‘while’ Loop for Time Delay

‘while’ loops can also be used to implement a time delay feature in your code. We can simply use the os.clock() function of Lua which returns the amount of CPU time used by Lua since this function was first called:

start = os.clock()
while os.clock() - start < 1 do end
print("This code was delayed by 1 second.")

The above ‘while’ loop will block the flow of control for 1 second before printing the message.

With this understanding of how ‘while’ loops function, and the variety of scenarios they can be applied to in Lua, we hope you feel empowered to take your Lua coding and game development skills to a whole new level.

Where to Go Next?

Now that you’ve mastered the nuances of the ‘while’ loop in Lua, you might be wondering what the next step in your game development journey is. We encourage you to continue exploring and mastering distinct elements and aspects of Lua, gaining more confidence and augmenting your skills with each new concept you learn.

In order to expedite this learning journey, we recommend you consider progressing with our Roblox Game Development Mini-Degree. This comprehensive curriculum includes a range of courses about game creation using Roblox Studio and Lua. It covers different game genres and even systems like multiplayer and leaderboards. Whether you’re a beginner or an experienced developer, this course offers hands-on learning opportunities that can enhance your expertise.

If you’d like to explore a wider range of learning resources, visit the Roblox section on our platform. With over 250 supported courses, Zenva offers beginner to professional levels in programming, game development, and AI to help you build a solid foundation for your future career.

Conclusion

The ‘while’ loop in Lua is indeed a powerful tool, capable of elevating your game development skills remarkably. Though it might seem simple at first glance, mastering its myriad applications bolsters your flexibility and control when designing game mechanics or handling data. Always remember: in the universe of coding, every new concept you grasp is a step towards unlocking your potential to create more complex, dynamic, and engaging games.

As you continue your journey into the realm of programming and game creation, don’t forget that we’re here to support you. Our comprehensive array of courses, such as ourRoblox Game Development Mini-Degree, is purposefully designed to pave your pathway to success. Embark on this exciting journey with us, and let’s make game creation easy, enjoyable, and extraordinary together.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

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