Why doesn't 'for k,v in t do' work anymore?

This is one of the few big changes between Lua 5.0 and 5.1. Although easy on the fingers, the old notation was not clear as to exactly how the key value pairs are generated. It was the equivalent of an explicit pairs(t), and so isn't suitable for the common case of wanting to iterate over the elements of an array in order.

In the for statement, t must be a function. In the simplest case, it must be a function that returns one or more values each time it is called, and must return nil when the iteration is finished.

It is very straightforward to write iterators. This is a simple iterator over all elements of an array which works just like ipairs:

function iter(t)
 local i = 1
 return function()
 local val = t[i]
 if val == nil then return nil end
 local icurrent = i
 i = i + 1
 return icurrent,val
 end end for i,v in iter {10,20,30} do print(i,v) end



Back