On Sat, May 22, 2010 at 11:33 AM, Joshua Jensen
<jjensen@workspacewhiz.com> wrote:
I am still fond of 'for k,v in t do'. I was very sad to see it go. It
was
simple. Lua is supposed to be simple, but ipairs/pairs complicated it.
Josh
Could we perhaps return to "for k,v in t do", and have the generic-for
use the __pairs metamethod of its target as the iterator factory? If
no __pairs exists, default to next(). So this:
for k,v in t do
print(k, v)
end
would normally act like you used pairs(). But if you set a metatable:
setmetatable(t, {
__pairs = function(t)
return function(t, i)
i = i + 1
local v = t[i]
if v then
return i, v
end
end, t, 0
end,
})
then it iterates over the numeric indices in order. Further, you could
easily define a "false ipairs()" that returns a table with the __pairs
metamethod set:
function ipairs(t)
local copy = {}
for k,v in t do
copy[k] = v
end
return setmetatable(copy, {
__pairs = the_iter, -- same as above
})
end
~Jonathan