[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: iterating over ... ?
- From: Benoit Germain <bnt.germain@...>
- Date: Thu, 7 Apr 2011 09:25:04 +0200
2011/4/6 Sam Roberts
<vieuxtech@gmail.com>
...[n]
is syntactically invalid, the valid lua code would be:
(...)[n]
where the () discards all but the first value, behaving like:
v = ...
Right. However,
#...
is valid code, but I got bitten by that fact that doesn't do what I intuitively expected. It is equivalent to
#(...)
and gives the length of the first item in the vararg list, not the item count. After all, given a table t, #t yields (some) count of the elements of t, not the length of t[1].
> f= function(...) print(#...) end
> f("abc","def")
3
> f({"a","b","c","d"})
4
> f()
stdin:1: attempt to get length of a nil value
stack traceback:
stdin:1: in function 'f'
stdin:1: in main chunk
[C]: ?
Doesn't the language always know the number of items in ..., so that the
#... idiom could in theory return this number instead of being applied
to the first item?
If #... and ...[n] performed that way, it would be easy to iterate over the contents of ... (even when some elements are nil) without creating a temporary table or resorting to calling select to get the element count. In fact, I am not even sure that select( '#',...) would be useful anymore.
But of course, all this depends on two details:
1. the fact thatthe number of items in ... is computable, so that the behavior of the #... idiom can be changed.
2. the addition of a special ...[n] idiom.
--
Benoit.