lua-users home
lua-l archive

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




On Thursday, October 3, 2013, Leo Razoumov wrote:
On 10/3/13, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
>> On 10/2/13, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
>> >> Another habit we should not be practicing is thinking of Lua tables as
>> >> having
>> >> array and hash parts.
>> >
>> > Exactly. This is an implementation detail for getting performance and
>> > reduced
>> > memory usage but Lua tables remain what they are: associative arrays.
>> >
>>
>> Unfortunately, Lua itself encourages such a separation and provides both
>> pairs and ipairs to reinforce the distinction.
>
> pairs traverses all keys, ipairs traverses integer keys starting from
> 1. They have NOTHING TO DO with whether those keys live in the array
> part or the hash part of a table. (How many times we will have to
> repeat this?)

Roberto,
I am not talking about implementation (hash part or array part) but about
table semantics. Lua table distinguishes sequential keys (from 1 through N)
that can be iterated in order using ipairs from the other keys iterated
via pairs that visit all the keys in a non-specified order.
Moreover, sequential keys lack length operator, for #tbl does not
necessarily return N.

Quick question: I know how to iterate sequential part forwards from 1 to N
using ipairs. How can I iterate it backwards from N down to 1?
I am afraid Lua does not provide a convenient way to find out the value of N.

Another related question: How can I iterate sequential part of a table
from 1 through N visiting only even (or odd) elements?

--Leo--


Leo,

Yes it does. This is always true:

local i 

for idx, v in ipairs(t) do 
  i = idx
end

assert (i == #t)

-andrew