• Skip to main content
  • Skip to after header navigation
  • Skip to site footer

Free-Mail

  • Events
  • Images
    • Instagram Goodness
  • Music
  • News
  • Software

Get to know Lua for loops in 4 minutes

Get to know Lua for loops in 4 minutes: Get to know Lua for loops in 4 minutes Seth Kenlon Wed, 11/30/2022 – 03:00

In programming, iteration is an important concept because code often must scan over a set of data several times so that it can process each item individually. Control structures enable you to direct the flow of the program based on conditions that are often established dynamically as the program is running. Different languages provide different controls, and in Lua, there’s the while loop, for loop, and repeat until loop. This article covers for loops. I will cover while and repeat until loops in a separate article.

For loop

A for loop takes a known quantity of items and ensures that each item is processed. An “item” can be a number. It can also be a table containing several entries or any Lua data type. The syntax and logic are a little flexible, but the syntax allows for these parameters, each of which essentially describes a counter:

  • Starting value of the counter
  • Stop value
  • The increment you want the counter to advance

For instance, suppose you have three items and want Lua to process each. Your counter could start at 3 and last until 1, at an increment of -1. That renders the count of 3, 2, 1.

 
mytable = { "zombie", "Halloween", "apocalypse" }

for count = 3, 1, -1 do
  print(count .. ": " .. mytable[count])
end

Run the code to ensure all three items are getting processed:

 
$ lua ./for.lua
3: apocalypse
2: Halloween
1: zombie

This code effectively processed the table in “reverse” because it was a countdown. You can count up, instead:

 
for count = 1, 3, 1 do
  print(mytable[count])
end

This example processes the table from lowest index to highest:

 
$ lua ./for.lua
1: zombie
2: Halloween
3: apocalypse

Increments

You can change the increment, too. For instance, maybe you want a zombie apocalypse without all the pomp and circumstance of Halloween:

 
mytable = { "zombie", "Halloween", "apocalypse" }

for count = 1, 3, 2 do
  print(mytable[count])
end

Run the code:

 
$ lua ./for.lua
zombie
apocalypse

The example printed 1 and 3 because the first count was 1, which was then incremented by 2 (for a total of 3).

Counter

Sometimes you don’t know the number of times you need Lua to iterate over data. In this case, you can set your counter to a variable populated by some other process.

Also, the word count isn’t a keyword. It’s just what I’m using in my sample code for clarity. It’s common for programmers to use something shorter, such as i or c.

 
var = os.time()

if var%2 == 0 then
  mytable = { var }
else
  mytable = { "foo", "bar", "baz" }
end

for c = 1, #mytable, 1 do
  print(mytable[c])
end

Programming and development
Red Hat Developers Blog
Programming cheat sheets
Try for free: Red Hat Learning Subscription
eBook: An introduction to programming with Bash
Bash shell scripting cheat sheet
eBook: Modernizing Enterprise Java
An open source developer’s guide to building applications

This code creates a variable containing the timestamp of when it was launched. If the timestamp is even (it has a modulo of 0 when divided by 2), then just the timestamp is placed into a table. If the timestamp is odd, it puts three strings into a table.

Now you can’t be sure how many times your for loop needs to run. It’s either once or thrice, but there’s no way to be sure. The solution is to set the starting count to 1 and the final count to the length of the table (#mytable is the built-in shortcut to determine the length of a table).

It might take a few times of running the script to see both results, but eventually, you end up with something like this:

 
$ lua ./dynamic.lua
1665447960

$ lua ./dynamic.lua
foo
bar
baz

For loops with pairs and ipairs

If you’ve already read my article on table iteration, then you’re already familiar with one of the most common for loops in Lua. This one uses the pairs or ipairs function to iterate over a table:

 
mytable = { "zombie", "Halloween", "apocalypse" }

for i,v in ipairs(mytable) do
  print(i .. ": " v)
end

The pairs and ipairs functions “unpack” the table and dump the values into the variables you provide. In this example, I use i for index and v for value, but the variables’ names don’t matter.

 
$ lua ./for.lua
1: zombie
2: Halloween
3: apocalypse

For loop

The for loop structure is common in programming and very common in Lua due to its frequent use of tables and the pairs function. Understanding the for loop structure and the options you have when controlling it means you can make clever decisions about how to process data in Lua.

Understanding the for loop structure and the options you have when controlling it means you can make clever decisions about how to process data in Lua.

arrows cycle symbol for failing faster
Image by:

Opensource.com

Programming

What to read next
How to use loops in awk

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.
Register or Login to post a comment.

: Opensource.com Seth Kenlon

Supporting Open Source.

Have you tried: Visiting Port Elizabeth?

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • Share on Pinterest (Opens in new window) Pinterest
  • Email a link to a friend (Opens in new window) Email
  • More
  • Share on Tumblr (Opens in new window) Tumblr
  • Print (Opens in new window) Print
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on Reddit (Opens in new window) Reddit
Published on 30 November 2022 by Alan Category: SoftwareTag: Know, Loops, Minutes

Trending Now: Dante Liang

These are the latest trending searches on Google right now: Dante Liang: : Daily Search Trends Pro …

Read moreTrending Now: Dante Liang

medano_111026_0582-Edit

A nice Strand Beach image: medano_111026_0582-Edit Image by Raico Rosenberg.com Image automatically …

Read moremedano_111026_0582-Edit

An Evning of Romance

An Evning of Romance – a Music interest event taking place on 2018-02-09 18:30:00 in United …

Read moreAn Evning of Romance

About Alan

Previous Post:Is sustainability still a thing in open source?
Next Post:Ending HIV as a public health threat – 3 essential reads

Reach Trust

Reach Trust is a holding trust for a number of companies within the Stratlec Group.

Copyright © 2026 · Free-Mail · All Rights Reserved · Powered by Straton Electrical

Back to top