lua-users home
lua-l archive

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


As the discussion of loops seems to have gone prematurely cold since the un-deprecation of ipairs, I figure I'd resurface one of the ideas that had been roughly proposed in the discussion: making table traversal loops part of the core language, rather than just iterator functions.

One type of loop would visit every key in a table once, operating similarly to pairs():

  for k, v over t do
    -- code...
  end

would be equivalent to

  do
    local k, v
    k = next(t)
    while k do
      v = t[k]
      -- code...
      k=next(t,k)
    end
  end

The other new type of loop would iterate from 1 to the first hole in the table, conceptually similar to ipairs():

  for i, v thru t do
    -- code...
  end

would be equivalent to

  do
    local i, v
    i = 1
    while t[i] do
      v = t[i]
      -- code...
      i=i+1
    end
  end

The generic for would remain for other iterators, such as io.lines().

The advantages of this:
* Reduced overhead, likely leading to increased performance
* Simpler execution for the two most common loops
* Two less standard functions in the global namespace

The disadvantages:
* Two more forms of the "for" loop