lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I get it, it just seems more complicated. Eg, consider simple proxy tables:

tab = {"apple", "banana", "pear"}
proxy = setmetatable({}, {
 __index = function(self, key)
   print("reading key: "..key)
   return tab[key]
 end })
for i,v in ipairs(proxy) do print(v) end

If ipairs used respected __index it'd print "apple", "banana", "pear" just fine. In Lua 5.2, you'd need to do this to achieve the same result:

tab = {"apple", "banana", "pair"}
function ipairshelper(tab, var)
 var = var + 1
 local v = tab[var]
 if value == nil then return end
 return var, value
end
proxy = setmetatable({}, {
 __index = function(self, key)
   print("reading key: "..key)
   return self[key]
 end,
 __ipairs = function(self)
   return _ipairshelper, tab, 0
 end, })
for i,v in ipairs(proxy) do print(v) end

It seems like a lot more work.

I guess the advantage is that you can make ipairs work in any way you want. Eg, it's not forced to start at 1, or to move in order through the array.

Still, that scares me a bit... for even this simple function:

local array = {}
for i,v in ipairs(source) do
 array[i] = v
end

Can under the new system give you holey arrays, given an appropriate source. Something that would be impossible with the standard ipairs in Lua 5.1 or with one that respects __index.

I dunno. Maybe I'm just afraid of change ;)

- Alex

----- Original Message ----- From: "Roberto Ierusalimschy" <roberto@inf.puc-rio.br>
Second, in my opinion, __index and __ipairs (whatever the final
semantics may be) are not comparable. __index is triggered on access
to non-existent keys and __ipairs would be used to redefine the way an
array-like table is iterated, right?

Right. (The semantics is that __ipairs, if present, is called and its
result is the final result of ipairs. So __ipairs is not called on
each iteraction; it is called before the loop to return an iteraction
function.)

-- Roberto