lua-users home
lua-l archive

RE: Iteration and nils

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


Luis Carvalho wrote:
>> The recent thread about lists and nil got me thinking about the ways
>> in which nil isn't a first-class data type in Lua. Of course, the
>> focus of that thread was on sparse arrays and vararg lists. I've
>> been thinking about another limitation of nil -- that the generic
>> for loop doesn't allow an iterator to provide nil as a value.
> 
> <snip>
> 
> Another approach -- already mentioned several times here -- is to use
> tuples. 
> You could then pass and return tuples to/from vararg functions. It
> would be easy to iterate over them (similarly to ipairs but checking
> for the number of arguments instead of a nil value), and the
> iteration would respect nils. Moreover, tuples can be implemented as
> closures and no change to the language would be necessary (a new
> datatype is a big change, btw). 
I thought that a new iterator on ... would solve the problem without
having to modify the language. I found out while looking for 'apairs'
that it was proposed last year by Mark Hamburg [1], with the name
varargs(), Mike Pall [2] proposing a more elegant apairs() name.
Unfortunately neither of them proposed an implementation. Since it's
trivial 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
function f(...)
 for i,a in apairs(...) do
 print(i, a)
 end
end
f("foo", nil, 32, nil)
[1] http://lua-users.org/lists/lua-l/2006-04/msg00108.html
[2] http://lua-users.org/lists/lua-l/2006-04/msg00114.html

AltStyle によって変換されたページ (->オリジナル) /