lua-users home
lua-l archive

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


PA wrote:

>> At first glance there are 4 different ways to write a
>> "for" loop ( "=", "in", "in ipairs()", "in pairs()" ).
>
> Let make that 5. There is a "in next()" as well. Sigh...

At second glance, you can think of there being three:  A
numeric one that just iterates through different numbers:

  for i = start, end do

and two "foreach"-type loops that iterate through elements
of a table:

  for k, v in pairs(t) do
  for i, v in ipairs(t) do

(Which one you use depends on how you've populated the
table.)

It's well worth the trouble to wrap your head around the
generic 'for' so that you can write your own iterators or do
hacks with the stock ones, but until you do, just think of
the other types of 'for' as being power-user stuff that you
can safely ignore -- other languages get by with much less
powerful loop constructs.  (I admit that this advice is less
helpful when reading someone else's code rather than writing
your own.)

By the way (you may already know this), the

  for k, v in t do

syntax is just a deprecated way of writing

  for k, v in pairs(t) do

-- 
Aaron

"PHP combines the orthogonality of sh with the elegance
of <font color=ad0000> Fatal error: Cannot redeclare
quuxitate() (previously declared in -:4) in - on line 6
</font>