Stateless vs stateful iterators
- Stateful iterators have been given as examples in prior code segments
- Stateless iterators must:
- Pass the state out to the calling code in the return statement
- Usually the return statement passes multiple values
- Pass the state in from the calling method in the function arguments
- Pass the state out to the calling code in the return statement
Examples of this are ipairs and pairs
- ipairs iterates over the portion of a table without holes
- pairs iterates over the entire table (in any order)
local orchestra = {'violin', 'trumpet', 'clarinet', 'tuba', 'guitar', 'flute'} for i, instrument in ipairs(orchestra) do print ("Instrument" .. i .. " " .. instrument) end orchestra = {[1] = 'violin', [2] = 'trumpet', [6] = 'clarinet', [18] = 'tuba', [20] = 'guitar', [3] = 'flute'} for i, instrument in pairs(orchestra) do print ("Instrument" .. i .. " " .. instrument) end
Results are
- Note that the second set are not in order
Instrument1 violin Instrument2 trumpet Instrument3 clarinet Instrument4 tuba Instrument5 guitar Instrument6 flute Instrument1 violin Instrument20 guitar Instrument2 trumpet Instrument18 tuba Instrument3 flute Instrument6 clarinet ``` _Behind the covers something like the following is doing the iteration_ * From the Lua website [Stateless Iterators](http://www.lua.org/pil/7.3.html) ``` function iter (a, i) i = i + 1 local v = a[i] if v then return i, v end end function ipairs (a) return iter, a, 0 end ```