lua-users home
lua-l archive

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


On Fri, 15 Aug 2014 15:44:11 +0200
Jan Behrens <jbe-lua-l@public-software-group.org> wrote:

>   function alternate_ipairs(t)
>     print("Evaluating length here!")
>     return alternate_ipairs_aux, t, #t, 0  -- not a triplet but a quadruple
>   end

As a matter of taste, it would also be possible to append any extra
state variables to the end of the triplet, rather than inserting them
in the middle:

========================================
function another_for(args)
  local f, s, var = table.unpack(args.explist)
  local extras    = {select(4, table.unpack(args.explist))}
  local block     = args.block
  while true do
    local results = {f(s, var, table.unpack(extras))}
    if results[1] == nil then break end
    var = results[1]
    block(table.unpack(results))
  end
end

do
  local function another_ipairs_aux(t, i, maxn)
    if i < maxn then
      i = i + 1
      return i, t[i]
    else
      return nil
    end
  end
  function another_ipairs(t)
    print("Evaluating length here!")
    return another_ipairs_aux, t, 0, #t  -- not a triplet but a quadruple
  end
end

t = {"a", "b", "c"}

another_for{explist = {another_ipairs(t)}, block = function(i, v)
  print(i, v)
end}
-- results in:
-- Evaluating length here!
-- 1   a
-- 2   b
-- 3   c
========================================

For example allowing construct as follows:

========================================
do
  local function iterate_aux(t, i, e)
    if i < e then
      i = i + 1
      return i, t[i]
    else
      return nil
    end
  end
  function iterate_from_to(tbl, from, to)
    return iterate_aux, tbl, from - 1, to  -- return a quadruple
  end
end

t = {"a", "b", "c"}

for i, v in iterate_from_to(t, 1, 2) do
  print(i, v)
end
-- would print:
-- 1   a
-- 2   b
========================================


Regards
Jan