lua-users home
lua-l archive

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


Once one adds __ipairs as a metamethod and __len is respected then I am thinking that ipairs() is sort of redundant.

By my benchmarks
for i =1, #t is 3 fold faster than for k,v in ipairs().

Also ipairs in Lua (half the speed) is trivially like:

local function ipairs(t)
  return function(s,i)
    local i = i + 1
    local v = s[i]
    if v == nil then i = nil end
    return i,v,i
  end ,t,0
end

So I think, there is no performace reason and convenience reason for ipairs(). If one really needs it then coding it in Lua is not traumatic.

This approach on the problem saves some documentation, adds some flexibility and would save a lot of Lua list mail server storage.

The thing is that I am beginning also to think that there is merit in the idea of __next rathere than __ipairs/__pairs, the only downside is that __next then requires rawnext() and lua_rawnext(), but it has the advantage of only one additional metatmethod and I think it is more in keeping with the language.

just my 2c
DB





On 15/1/2010 12:43 PM, Renato Maia wrote:

On 14 Jan 2010, at 22:51, Klaus Ripke wrote:
On Sat, Jan 09, 2010 at 12:52:33PM +0300, Alexander Gladysh wrote:
On Sat, Jan 9, 2010 at 12:37, steve donovan
<steve.j.donovan@gmail.com> wrote:
2010/1/9 Ignacio Burgueño <ignaciob@inconcertcc.com>:
17. Documented behaviour of ipairs() is changed from "iterates until
*first nil*" to "traverses table length elements as defined by length
operator".

This is more consistent, but given how strange #t is when t has a
number of holes, it isn't necessarily more useful.

(1) Don't have holes in tables you want to measure with #, that's all.

That's why this change to rely on #t is completely beyond me.

It might be intended for tables that redefine the meaning of #:

Lua 5.2.0 (work2) Copyright (C) 1994-2010 Lua.org, PUC-Rio
 > m={}
 > m.__len = function() return 3 end
 > m.__index = function(_, ...) return ... end
 > t = setmetatable({}, m)
 > for k,v in ipairs(t) do print(k,v) end
1 nil
2 nil
3 nil

As much as I love those metamethods tricks, I must say they seem to me
more scary than useful when they do not come with their 'raw*'
counterparts. I remember pretty well how it felt the few times all I
wanted was a 'rawtostring', so I rather not think how it will feel nor
the many times I might be hoping for a 'rawipairs' in the future. (or a
'rawlen' for that matter)

--
Renato Maia
Computer Scientist
Tecgraf/PUC-Rio
__________________________
http://www.inf.puc-rio.br/~maia/