Looping Through Tables

From PZwiki
Jump to: navigation, search
Language policy Language: [[::Looping Through Tables|English]]

As covered in the last tutorial, you can access individual fields easily. However, there may be times when you want to use all the key-value pairs stored in table. For this, we use loops.

Firstly, lets create a table:

week  = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}

If you try print(week) you'll notice all you get is Lua's reference for that table. To view all the values in arrays, we can use a special for loop called ipairs:

for i,v in ipairs(week) do
print(i, v)

As you can see, i is assigned all the keys, and v all the values. Like mentioned in the loops tutorial, these are local variables discarded each cycle.
ipairs only works for arrays without any gaps. It works by iterating over the key-value pairs until key=nil and key+1=nil. Note that you can also use a regular loop to go through an array:

for i = 1, #week do
print(i, week[i])

For associative tables we can use a slight variation, in pairs:

Bob = {}
Bob.health = 50
Bob.weapon = "Axe"
Bob.hunger = 100

for i,v in pairs(Bob) do
print(i, v)

This returns all key-value pairs, but in an unpredictable order.


  • You can use an ipairs to looop through arrays
  • Or use a regular for loop and the length operator
  • You can use pairs loop for associative tables, but the order of returned values is unpredictable