lua-users home
lua-l archive

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

Jerome Vuarand <jerome.vuarand <at>> writes:
> I found out while looking for 'apairs'...
> here is a simple (tested) implementation:
> function apairs(...)
>   local n = select('#', ...)
>   return function(a, i)
>     if i < n then
>       return i+1,a[i+1]
>     end
>   end, {...}, 0 
> end

Here's a similar form that avoids creating the closure:

local function helper(a, i)
  if i < a.n then return i+1,a[i+1] end
function apairs(...)
  return helper, {n=select('#', ...), ...}, 0

-- test
function f(...)
  for i,a in apairs(...) do print(i, a) end
f("foo", nil, 32, nil)