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

Free-Mail

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

How to iterate over tables in Lua

How to iterate over tables in Lua: How to iterate over tables in Lua Seth Kenlon Fri, 11/04/2022 – 03:00

In the Lua programming language, an array is called a table. A table is used in Lua to store data. If you’re storing a lot of data in a structured way, it’s useful to know your options for retrieving that data when you need it.

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

Creating a table in Lua

To create a table in Lua, you instantiate the table with an arbitrary name:

 mytable = {}

There are different ways you can structure your data in a table. You could fill it with values, essentially creating a list (called a list in some languages):

 mytable = { 'zombie', 'apocalypse' }

Or you could create an associated array (called a map or dictionary in some languages). You can add arbitrary keys to the table using dot notation. You can also add a value to that key the same way you add a value to a variable:

 
myarray = {}
myarray.baz = 'happy'
myarray.qux = 'halloween'

You can add verification with the assert() function:

 
assert(myarray.baz == 'happy', 'unexpected value in myarray.baz')
assert(myarray.qux == 'halloween', 'unexpected value in myarray.qux')

You now have two tables: a list-style mytable and an associative array-style myarray.

Iterating over a table with pairs

Lua’s pairs() function extracts key and value pairs from a table.

 
print('pairs of myarray:')

for k,v in pairs(myarray) do
  print(k,v)
end

Here’s the output:

 
pairs of myarray:
baz     happy
qux     halloween

If there are no keys in a table, Lua uses an index. For instance, the mytable table contains the values zombie and apocalypse. It contains no keys, but Lua can improvise:

 
print('pairs of mytable:')

for k,v in pairs(mytable) do
  print(k,v)
end

Here’s the output:

 
1   zombie
2   apocalypse

Iterating over a table with ipairs

To account for the fact that tables without keys are common, Lua also provides the ipairs function. This function extracts the index and the value:

 
print('ipairs of mytable:')

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

The output is, in this case, the same as the output of pairs:

 
1   zombie
2   apocalypse

However, watch what happens when you add a key and value pair to mytable:

 
mytable.surprise = 'this value has a key'

print('ipairs of mytable:')

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

Lua ignores the key and value because ipairs retrieves only indexed entries:

 
1   zombie
2   apocalypse

The key and value pair, however, have been stored in the table:

 
print('pairs of mytable:')

for k,v in ipairs(mytable) do
  print(k,v)
end

The output:

 
1          zombie
2          apocalypse
surprise   this value has a key

Retrieving arbitrary values

You don’t have to iterate over a table to get data out of it. You can call arbitrary data by either index or key:

 
print('call by index:')
print(mytable[2])
print(mytable[1])
print(myarray[2])
print(myarray[1])

print('call by key:')
print(myarray['qux'])
print(myarray['baz'])
print(mytable['surprise'])

The output:

 
call by index:
apocalypse
zombie
nil
nil

call by key:
halloween
happy
this value has a key

Data structures

Sometimes using a Lua table makes a lot more sense than trying to keep track of dozens of individual variables. Once you understand how to structure and retrieve data in a language, you’re empowered to generate complex data in an organized and safe way.

Create structure that makes it easier to find stored data.

Programming keyboard.
Image by:

Opensource.com

Programming

What to read next
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: Farking?

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 4 November 2022 by Alan Category: SoftwareTag: iterate, Over, Tables

Cool Cape Town Day 8 072 image

A cool Cape Town image: Cape Town Day 8 072 Image by Karmor Image automatically curated and …

Read moreCool Cape Town Day 8 072 image

Coronavirus: how school closures affect infection numbers

Coronavirus: how school closures affect infection numbers: Zorro Stock Images/Shutterstock Whether …

Read moreCoronavirus: how school closures affect infection numbers

Water Lantern Festival Madison

Water Lantern Festival Madison – a Beauty interest event taking place on 2020-08-22 17:00:00 …

Read moreWater Lantern Festival Madison

About Alan

Previous Post:Cool Küste Fecamp image
Next Post:Malaria in Africa: why most countries haven’t beaten it yet

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