for (generic)

The generic for lets you loop under the control of an iterator, eg.
for key, value in pairs (my_table) do
  print (key, value)
end 
The keyword in distinguishes the "generic for" from the "numeric for".

The "generic for" requires three expressions after the word "in" (which might be supplied by a function call such as pairs or ipairs): The equivalent of using pairs (my_table) is to do this:
for key, value in next, my_table, nil do
  print (key, value)
end 
In this case "next" is the iterator function, my_table is the state value, and nil is the initial value to be passed to the iterator.


If you want to leave the loop from inside you can use a break statement.

You should not attempt to change the loop control variable (the first value returned). Doing so will lead to undefined results.

You don't normally need to be too concerned about the inner details of the "generic for". Often it is used to traverse tables by using the functions pairs or ipairs which return the correct iterators and initial values. For example:
t = { "every", "good", "boy", "deserves", "fruit" }

for key, value in pairs (t) do
  print (key, value)
end -- for
Results:
1 every
2 good
3 boy
4 deserves
5 fruit



More specifically what happens in the generic "for" is: The "next" function is an example of an iterator function. It takes a table and current key, and returns the key/value pair of the next entry. The current key can then be used to get the next one again, and so on. Since the "next" function returns the first key in the table if the "current key" is nil, then we initially start off with nil as the iterator variable.

Lua keyword/topics

Topics