for (generic) |
---|
The generic for lets you loop under the control of an iterator, eg.
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): An iterator function: "f" A state value: "s" An initial value of the iterator variable: "i" The equivalent of using pairs (my_table) is to do this:
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:
Results:
More specifically what happens in the generic "for" is: The three expressions are evaluated once before the loop starts. The first argument must be a function (the iterator function). The iterator function is called with both the state "s" and the iterator variable "i". The state might be a table we are traversing, and the iterator variable might be how far through that table we are. In effect:
The first value returned by the iterator function becomes the iterator variable for the next round. If the first value returned by the iterator function is nil the loop terminates. Otherwise the body of the loop executes and then the process (of calling the iterator function onwards) is repeated. 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. See Also ... Lua keywords/topics
assignment
Topics
Lua base functions
(Help topic: lua=for (generic)) |
Enter a search string to find matching documentation.
Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.